0
votes

I am trying to dynamically extend Backbone.js view's render function. In doing so, I want to be able to fire an event before and after render is being called. I have tried overwriting the function and call the old function, which works, but all models that bind to the render function lose their bindings. The code that I currently have is the following, were I pass in a created Backbone.js view:

function bindRenders(view) {

    view.render = (function() {
        var cachedRender = view.render;

        return function() {
            console.log("before render");
            cachedRender.apply(this, arguments);
            console.log("after render");
        };
    }());
}

Again, the above code will work, but all models that are bound to the render function by:

    this.model.on('change', this.render, this);

break. The only solution I have found is to rebind the .on('change') event of the model after I overwrite the function. However, not every view's model will be bound in this fashion. Any help is very much appreciated! Thanks!

1

1 Answers

1
votes

What do you mean 'break' ? your previous render code still gets called when the model changes ?

That's because the function that is bound to the 'change' event is not your new one, you're simply changing the property 'render' of your view, not what gets executed on change. I guess that would work if your binding was : this.model.on('change', function(){return this.render()}, this)

But I can't see why you would want that. In my opinion, you should use inheritance to apply this kind of common behaviors.

Something like (much simplified)

var MyBaseView = Backbone.View.extend({
  ...
  render: function(){
    this.trigger('beforeRender');
    this.beforeRender()

    //do something generic
    ...

    this.afterRender()
    this.trigger('afterRender');
  }
  ...
});

var MyOtherView = MyBaseView.extend({
  ...
  beforeRender: function(){
    //do something specific
  }

  //do NOT override "render"

  afterRender: function(){
    //do some other specific things
  }
  ...
});

Or a much better solution like this one Backbone.js view inheritance

Also I suppose that https://github.com/tbranyen/backbone.layoutmanager has a lot of what you want to achieve.