2010-11-29 31 views
0

開發環境:HP/Palm WebOS,帶SDK 1.4.5.465的Eclipse,Win7如何聲明和監聽自定義事件?

我有一個類,我想聲明並在某些情況下觸發一個事件。然後,在相應的階段,助理傾聽該事件,並在提出時做一些事情。

閱讀引用我遇到過Mojo.Event.make,Mojo.Controller.stageController.sendEventToCommanders,Mojo.Event.send和我認爲與我想要實現的內容有關的一些內容,但是我沒有找到一個特別的例子(聲明,解僱和聆聽)。爲了澄清,我想觸發的事件與一個小部件或一個帶有id的html標記無關。

回答

0

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; 

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