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;
的这种模式最大的局限性在于,只能有一个对象倾听特定事件,但在某些情况下,您只需要这些。