Delegating events to a parent view in Backbone

后端 未结 3 2151
感动是毒
感动是毒 2021-02-14 19:08

My view, TuneBook, has several child views of type ClosedTune. I also have separate full page views for each tune, OpenTune. The same even

3条回答
  •  既然无缘
    2021-02-14 19:57

    In your parent view (extending also from Backbone.Events), I would bind onEvent to the DOM event. On trigger, it would fire a backbone event including some "id" attribute that your child views know (presumably some row id?).

    var TuneBook = Backbone.View.extend(_.extend({}, Backbone.Events, {
        events: {
            "click .tune .button": "clickHandler"
        },
        clickHandler: function (ev) {
            this.trigger('buttonClick:' + ev.some_id_attr, ev);
        },
    
    }));
    

    Child views would then naturally subscribe to the parent views event that concerns them. Below I do it in initialize passing the parent view as well as that special id attribute you used before in options.

    var ClosedTune = Backbone.View.extend({
    
        initialize: function (options) {
            options.parent.on('buttonClick:' + options.id, this.handler, this);
        },
    
        handler: function (ev) {
            ...
        },
    
    });
    

    You can of course also set up similar subscribers on Tune or OpenTune.

提交回复
热议问题