0

I'm trying to add a language support in my website and I need to add this code so it will run before marionette render in all the views no matter which type.

onBeforeRender: function(){

    var helpers = this.templateHelpers();
    this.templateHelpers = function(){
        return $.extend( (helpers), {
            lang : function () {
                return function(val, render) {
                    return lang(val);
                }
            }
        });
    }
}

I don't want to extend all the views and put this code in each of them, I wonder if there is a way to just put this code in some place and it will run before every render

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
roy
  • 585
  • 5
  • 14

2 Answers2

3

You should be able to extend the prototype with something like

_.extend(Marionette.View.prototype, {

    onBeforeRender: function(){

        var helpers = this.templateHelpers();
        this.templateHelpers = function(){
            return $.extend( (helpers), {
                lang : function () {
                    return function(val, render) {
                        return lang(val);
                    }
                }
            });
        }
    }

})

Naturally, that means that if one of your marionette views defines its own onBeforeRender, you'll need to call the implementation on the View prototype "by hand".

David Sulc
  • 25,946
  • 3
  • 52
  • 54
0

I think you should create a view mixin with your code and extend every view with this mixin

var LangMixin = { 
    onBeforeRender: function(){
        var helpers = this.templateHelpers();
            this.templateHelpers = function(){
                return $.extend( (helpers), {
                    lang : function () {
                    return function(val, render) {          
                        return lang(val);
                        }                                                                       
                    }   
                }); 
           }            
    }
}   

var YourView= Backbone.View.extend({
     // ...
});

_.extend(YourView.prototype, LangMixin);
Community
  • 1
  • 1
kharandziuk
  • 12,020
  • 17
  • 63
  • 121