Backbone View: Inherit and extend events from parent

前端 未结 15 627
醉梦人生
醉梦人生 2020-11-30 16:50

Backbone\'s documentation states:

The events property may also be defined as a function that returns an events hash, to make it easier to programmatic

相关标签:
15条回答
  • 2020-11-30 17:35

    Wow, lots of answers here but I thought I'd offer one more. If you use the BackSupport library, it offers extend2. If you use extend2 it automatically takes care of merging events (as well as defaults and similar properties) for you.

    Here's a quick example:

    var Parent = BackSupport.View.extend({
        events: {
            change: '_handleChange'
        }
    });
    var Child = parent.extend2({
        events: {
            click: '_handleClick'
        }
    });
    Child.prototype.events.change // exists
    Child.prototype.events.click // exists
    

    https://github.com/machineghost/BackSupport

    0 讨论(0)
  • 2020-11-30 17:36

    // ModalView.js
    var ModalView = Backbone.View.extend({
    	events: {
    		'click .close-button': 'closeButtonClicked'
    	},
    	closeButtonClicked: function() { /* Whatever */ }
    	// Other stuff that the modal does
    });
    
    ModalView.extend = function(child) {
    	var view = Backbone.View.extend.apply(this, arguments);
    	view.prototype.events = _.extend({}, this.prototype.events, child.events);
    	return view;
    };
    
    // MessageModalView.js
    var MessageModalView = ModalView.extend({
    	events: {
    		'click .share': 'shareButtonClicked'
    	},
    	shareButtonClicked: function() { /* Whatever */ }
    });
    
    // ChatModalView.js
    var ChatModalView = ModalView.extend({
    	events: {
    		'click .send-button': 'sendButtonClicked'
    	},
    	sendButtonClicked: function() { /* Whatever */ }
    });

    http://danhough.com/blog/backbone-view-inheritance/

    0 讨论(0)
  • 2020-11-30 17:40

    The soldier.moth answer is a good one. Simplifying it further you could just do the following

    var ChildView = ParentView.extend({
       initialize: function(){
           _.extend(this.events, ParentView.prototype.events);
       }
    });
    

    Then just define your events in either class in the typical way.

    0 讨论(0)
提交回复
热议问题