How to bind context of child view handling event in parent view

ε祈祈猫儿з 提交于 2020-01-16 09:41:13

问题


I have the following Backbone View's:

var ParentView = Backbone.View.extend({
     events: {
         "contextmenu .child-view" : "handleChildView"
     },

     initialize: function () {
        // create child view
        var child = new ChildView;
     },

     handleChildView: function () {
     }
});

var ChildView = Backbone.View.extend({

     initialize: function () {
        this.el.addClass('child-view');
     }
});

I need to handle childView's contextmenu event in handleChildView handler. But I need to get refference to childView and target DOM element.

How could I make this?


回答1:


I usually would try to avoid that. I think it's an anti-pattern since I believe each view should only handle it's own events.

When there's a need for notifying events between views, I use the event bus pattern.(publisher/subscriber)

see this answer I posted earlier:

Call a function in another Marionette.ItemView

It's similar.

You should define an event bus in your app. And in your ChildView, publish an event when something happens (like click)

var ChildView = Backbone.View.extend({
  events: {
    'click': 'handleClick'
  },
  handleClick: function() {
    //publish event
    EventBus.trigger('childViewClicked', [anything you wanna pass]);
  }
});

and in your parent view, subscribe to this event:

 var ParentView = Backbone.View.extend({
   initialize: function () {
     //subscribe events:
     EventBus.on('childViewClicked', this.handleChildView, this);
   },

   handleChildView: function ([params you wanna receive]) {
   }
 });



回答2:


Would this work for you?

var ParentView = Backbone.View.extend({
     events: {
         "click .child-view .contextmenu" : "handleChildView"
     },

     initialize: function () {
        // create child view
        var child = new ChildView;
     },

     handleChildView: function () {
     }
});

var ChildView = Backbone.View.extend({
     className:'child-view'
     , initialize: function () {
        this.el.addClass('child-view');
     }
});

You might have to render the child view inside the parent view (in the DOM)



来源:https://stackoverflow.com/questions/20227151/how-to-bind-context-of-child-view-handling-event-in-parent-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!