问题
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