2

Is it possible to override closeClick function in child view? When .close is clicked, only run child's closeClick function instead of the parent.

var ParentView = Backbone.View.extend({
 events:{
    "click .close": "closeClick"
 },

 closeClick: function(){
    //do parent stuff
 }
});

var ChildView = ParentView.extendable.extend({
  events:{
    "click .close": "closeClick",
    //more child events
  },

  closeClick: function(){
     //only do child stuff not parent when .close is clicked
  }
});
Akos K
  • 7,071
  • 3
  • 33
  • 46
bf39L
  • 149
  • 2
  • 14
  • I searched and tried this solution however not working http://stackoverflow.com/questions/9403675/backbone-view-inherit-and-extend-events-from-parent – bf39L Jun 30 '15 at 01:58
  • I tried to write return _.extend({},ParentView.prototype.events,{ 'click' : 'onclickChild' }); inside the child view, it cannot override the parent closeClick function, seems it can only extend more events – bf39L Jun 30 '15 at 02:09
  • Function name in child is whatever, just the child function can override the parent function. like if child function called "onclickChild", once .close on click, run onclickChild not the function in parent "closeClick", thanks! – bf39L Jun 30 '15 at 02:35
  • the function named "closeClick" inherited from parentview is overridden by the childView. So I guess childViews "closeClick" should get called.Just check out $el of childView if it refers to child's control with class "close" – nikhil mehta Jun 30 '15 at 05:15

1 Answers1

1

What you have written will work fine with normal Backbone .extend. Don't know what this strange extendable statement is though - that's probably what's breaking it.

var ParentView = Backbone.View.extend({
 events: {
    "click .close": "closeClick"
 },

 closeClick: function(){
    //do parent stuff
 }
});

var ChildView = ParentView.extend({
  events: function() {
    var parentEvents = _.result(ParentView.prototype, 'events');
    return _.extend({
        'keyup input': 'someOtherChildEvent'
    }, parentEvents);
  },

  closeClick: function() {
     //only do child stuff not parent when .close is clicked
  }
});
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • Hello There thanks for your answer. Just wonder can I bind "click .close": "childCloseClick" in ChildView? like return _.extend({ "click .close": "childCloseClick", 'keyup input': 'someOtherChildEvent' }, parentEvents); – bf39L Jun 30 '15 at 22:10
  • Np, if you repeat `click .close` there with a different method name, it will override the parent's one, so it will call `childCloseClick` instead of `closeClick` in the child view – Dominic Jun 30 '15 at 22:21