Backbone. Dispatch/listen to events between views

不羁的心 提交于 2019-12-09 05:18:44

问题


Im a bit confused over how to handle events between views in Backbone. Right now i have two partial views rendered at the same time on a website. Now i want one of the views to dispatch an event that the other view can listen to. How would i do that?

In the view that dispatches the event i run:

this.trigger("myEvent")

And in the view listening i run:

this.bind('myEvent', this.myFunc);

But nothing seem to happen at all.


回答1:


If you're triggering an event on v1 with:

this.trigger('myEvent'); // this is v1

then you'd have to listen to events from v1 with:

v1.on('myEvent', this.myFunc); // this is, say, v2 here.

The events aren't global, they come from specific objects and you have to listen to those specific objects if you want to receive their events.

If you bind the views directly to each other, you'll quickly have a tangled mess where everything is directly tied to everything else. The usual solution is to create your own event bus:

// Put this where ever it makes sense for your application, possibly
// a global, possible something your your app's global namespace, ...
var event_bus = _({}).extend(Backbone.Events);

Then v1 would send events through the event_bus:

event_bus.trigger('myEvent');

and v2 would listen to the event_bus:

this.listenTo(event_bus, 'myEvent', this.myFunc);

I've also switched from bind to listenTo since listenTo makes it easier to prevent zombies.

Demo: http://jsfiddle.net/ambiguous/yb9TY/



来源:https://stackoverflow.com/questions/20816810/backbone-dispatch-listen-to-events-between-views

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