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;
的這種模式最大的侷限性在於,只能有一個對象傾聽特定事件,但在某些情況下,您只需要這些。