开发者

How to call back the function?

I have this simple code.

myobj.job('first', function (one, two){

   console.log("First");

});

myobj.job('second', function (one, two){

   console.log("Second");

});

Now the question is开发者_如何学Go:

how myobj could call one of these depending on the event('first' or 'second') occurred?

Thanks


It's called observer pattern.

Here's an example implementation -- http://jsfiddle.net/6Jv5n/1


You'll probably be looking for more functionality in the future for event emitters/listeners so you might take a look at some ready built modules:

EventEmitter2

https://github.com/hij1nx/EventEmitter2

Features

  • Namespaced events Wildcards for
  • namespaces Times To Listen (TTL),
  • extends the once concept Browser
  • environment compatibility As good or
  • better performance for emission and
  • listener registration as Node.js core
  • EventEmitter Smaller.
  • EventEmitter2.js (2.2K Minified) VS.
  • events.js (2.7K Minified)

Hook.io

https://github.com/Marak/hook.io

hook.io creates a distributed node.js EventEmitter that works cross-process / cross-platform / cross-browser.

You create custom i/o scenarios by picking and choosing from an extensive library of tiny, independent, autonomous "hooks" that seamlessly work together.


Take a look at the source code for those and it'll give you a good idea how to work well with emitting events.


nodejs & EventEmitter answer: http://nodejs.org/docs/v0.4.9/api/events.html

function myobj()
{
   // constructor
}

util.inherits(myobj, process.EventEmitter)

myobj.prototype.hereComesEvent1 = function()
{
   // do stuff
   // ..
   // fire event
   this.emit('first', 1, 2);
}

myobj.prototype.hereComesEvent2 = function()
{
   // do stuff
   // ..
   // fire event
   this.emit('second', 'one', 'two');
}


// test myobj

var mo = new myobj();
mo.on('first', function(a, b) {
   console.log([a, b]);
});
mo.on('second', function(a, b) {
   console.log([a, b]);
});

mo.hereComesEvent1();
mo.hereComesEvent2();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜