如何声明和收听自定义事件?

时间:2010-11-29 15:52:37

标签: webos palm-pre

开发环境:HP / Palm WebOS,Eclipse with SDK 1.4.5.465,Win7

我有一个课程,我想宣布,在某些情况下,发动一个事件。然后,在相应的阶段助理听取该事件,并在它被提出时,做一些事情。

阅读参考资料我遇到过Mojo.Event.make,Mojo.Controller.stageController.sendEventToCommanders,Mojo.Event.send以及其他一些我认为与我想要达到的目标相关的内容,但是我找不到具体的例子(宣告,解雇和聆听)。

为了澄清,我想要触发的事件与小部件或带有id的html标签无关。

1 个答案:

答案 0 :(得分: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;

这个模型的最大限制是你只能有一个对象可以监听特定的事件,但在某些情况下你只需要它。