Backbone.js 全局事件 [英] Backbone.js global events
问题描述
关于 Backbone 中的事件的一个简单问题 - 有没有办法定义一组全局事件,可以在不同的视图中重复使用?
A quick question regarding Events in Backbone - is there any way to define a set of global events, which can be re-used in different views?
例如 - 假设我有几个在页面上呈现的视图.每个视图都有一个可以展开菜单的按钮.还有其他几个通用元素和事件.如果不将此事件逻辑放入每个视图中,有没有办法让这些视图中的每一个都可以继承,或者从全局事件定义中提取这些事件?通过在一个地方定义这些通用事件,它肯定会节省时间并成为更简洁的解决方案.
For instance - say I have several Views which are rendered on the page. Each View has a button that will expand a menu. There are also several other generic elements and events. Without putting this event logic into each View, is there a way that each of these Views could inherit, or pull these events from a global events definition? It would certainly save time and be a lot cleaner solution by defining these generic events in one place.
我看到过诸如事件聚合器和工厂模式之类的术语 - 但不确定最佳方法(或者它们是否会实现我所追求的).
I've seen terms such as Event Aggregator and Factory patterns thrown around - but not sure on the best approach (or if they will achieve what I'm after).
推荐答案
是的,您基本上是在描述事件聚合器或调度器.我有几篇关于在 Backbone 中构建和使用它们的文章:
You're basically describing an event aggregator or dispatcher, yes. I've got a couple of articles on building and using them with Backbone:
网络上有更多关于使用 Backbone 和其他发布/订阅库执行相同操作的文章.
And there are plenty more articles around the web for doing the same with Backbone and other pub/sub libraries.
在 Backbone 中很简单:
It's quite simple to do in Backbone:
vent = _.extend({}, Backbone.Events);
现在您有一个 vent
对象,可以在您的所有应用程序视图和其他对象中用作事件聚合器.
and now you have a vent
object that can be used as an event aggregator throughout all of your application's views and other objects.
vent.on("some:event", function(){
console.log("some event was fired");
});
vent.trigger("some:event");
这篇关于Backbone.js 全局事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!