开发者

how-to declare and listen custom events?

Developing environment: HP/Palm WebOS, Eclipse with SDK 1.4.5.465, Win7

I have a class in which I want to declare and under certain circumstances, fire an event. Then, in the corresponding stage assistant listen for that event, and when it's raised, do something.

reading the 开发者_开发技巧reference i've come across Mojo.Event.make, Mojo.Controller.stageController.sendEventToCommanders, Mojo.Event.send and a few more that i think are related to what i'm trying to achieve, but I fail to find an example especific to this (declaring, firing and listening).

To clarify, the event I want to fire is not related to a widget nor an html tag with an id.


Mojo.Event relies on the originator of the event being a node/element in an HTML document. From what I can tell there is no built in library for events outside of the DOM context so at this point you'll have to implement your own. Depending on how complex your situation is you may be able to get a way with just creating a property on the object you're listening to and storing a function that get's called a certain time in the future:

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;

The biggest limitation to this model is that you can only have one object listening to the particular event but in some situations that's all you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜