3

So I have this current situation:

app.Ui.ModalView = Backbone.View.extend({
    events: {

    },

    initialize: function() {

    },

    render: function() {
        var that = this;
        var model = this.model.toJSON();

        that.$el.html(that.template(_.extend(this.params || {}, {
            model: model,
        })));
        return this;
    }
});

and then the inherited view:

app.Views.childView = kf.Ui.ModalView.extend({

    template: JST["templates/app/blah/blah-edit.html"],
    events: {

    },
    initialize: function() {
        var that = this;
        this.events = _.extend({}, app.Ui.ModalView.prototype.events, this.events);
        app.Ui.ModalView.prototype.initialize.apply(this, arguments);
    },

render: function(){
// add extra logic in this render function, to run as well as the inherited render function?
}

});

So, I don't want to override the parent's render(), but to add extra functionality to it, how would I go about doing that?

benhowdle89
  • 36,900
  • 69
  • 202
  • 331

1 Answers1

8

Two ways to achieve this: Either you can add explicit support for overriding the behaviour by creating a "render hook" in the base class, or you'll have to call the overridden base method from the superclass method:

Render hook in base class:

app.Ui.ModalView = Backbone.View.extend({
  render: function() {
    //if this instance (superclass) defines an `onRender` method, call it
    if(this.onRender) this.onRender();

    //...other view code
  }
}

app.Views.childView = kf.Ui.ModalView.extend({
  onRender: function() {
    //your custom code here
  }
});

Call base class method from super class:

app.Views.childView = kf.Ui.ModalView.extend({
  render: function() {
    //your custom code here

    //call the base class `render` method
    kf.Ui.ModalView.prototype.render.apply(this, arguments);
  }
});
jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • @nikoshr, oopsie, fixed. The problem is that I tend to sometimes type faster than I think. Thanks. – jevakallio Jul 03 '13 at 09:57
  • 1
    You could also use Backbone's way of accessing a parent class: `this.construtor.__super__`. – Loamhoof Jul 03 '13 at 10:08
  • @Loamhoof it seems like using `__super__` is not recommended: https://github.com/jashkenas/backbone/pull/787#issuecomment-3143358 (I found this while reading http://stackoverflow.com/a/9170976/426790) – Greg Sadetsky Jan 31 '14 at 22:52