Mojo.Event 依赖于事件的发起者是 HTML 文档中的节点/元素。据我所知,没有用于 DOM 上下文之外的事件的内置库,因此此时您必须实现自己的。根据您的情况有多复杂,您可以通过在您正在收听的对象上创建一个属性并存储一个在未来某个时间调用的函数来获得一种方法:
ListeningObject = Class.create({
initialize:function(){
// instantiate instance of Subject
var subject = new Subject();
// set the onEvent property of subject to an instance of this.onEvent bound to
// a this instance of Listening object's context.
subject.onEvent = this.onEvent.bind(this);
subject.doSomethingAwesome();
},
onEvent:function(){
Mojo.Log.info("This get's called from the object we're listening to");
}
});
Subject = Class.create({
doSomethingAwesome:function(){
// does stuff, maybe an ajax call or whatever
// when it's done you can check if onEvent is a function and then
// you can call it, we'll use setTimeout to simulate work being done
setTimeout((function(){
if(Object.isFunction(this.onEvent)) this.onEvent();
}).bind(this), 200);
},
onEvent:null
});
// instantiate an instance of ListeningObject to see it in action
var listening_object = new ListeningObject;
此模型的最大限制是您只能让一个对象监听特定事件,但在某些情况下,这就是您所需要的。