简体   繁体   中英

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:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM