Delegating events to a parent view in Backbone

后端 未结 3 2147
感动是毒
感动是毒 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:58

    Great solution I have taken from this article (@dave-cadwallader comment).

    Extend an general backbone events object and store it in a reference vent:

    var vent = _.extend({}, Backbone.Events);
    

    Pass it to parent view:

    var parentView = new ParentView({vent: vent});
    

    The child view will trigger an event:

    ChildView = Backbone.View.extend({    
      initialize: function(options){
        this.vent = options.vent;
      },
    
      myHandler: function(){
        this.vent.trigger("myEvent", this.model);
      }
    });
    

    And the parent view is listening to the child event:

    ParentView = Backbone.View.extend({    
        initialize: function(options){
            this.vent = options.vent;
            this.vent.on("myEvent", this.onMyEvent);
    
            let childView = new ChildView({vent: this.vent});
        },
    
        onMyEvent: function(){
            console.log("Child event has been ");
        }
    });
    

    Disclaimer - pay attention that the vent object has to be injected to every view so you will find in this article better design patterns to make use of.

提交回复
热议问题