Observer
Simple observer to work with events. It can be used as a stand-alone observer or can be mixed in in some other object/function/class to directly reuse the functionality of an observer there.
All attached event handlers are stored in FIFO order. They are stored as is, i.e. if binding to some context is required then it should be done manually.
Requirements
It is written on vanilla JavaScript :)
It does not require any additional libraries.
Installation
$ npm install valerii-zinchenko/observer --save
$ grunt build
Available library files:
dest/observer.js
- not minified librarydest/observer.min.js
- minified library
The destination library files are surrounded with the universal module definition. So it can be loaded
- as a module for NodeJS
- as an AMD module
- or will be stored into the global variable under the name
Observer
Usage
Simple event with property
var observer = new Observer('hi', function(name) {
console.log('hi ' + name);
});
observer.listen('hi', function(name) {
console.log('hi ' + name + ' again');
});
observer.trigger('hi', 'world');
Example of encapsulating of Observer functionality into a class, by using a class-wrapper.
var Human = Class(function() {
this.listen('answer', this.onAnswer);
}, {
Encapsulate: Observer,
callCat: function(cat) {
cat.trigger('call', this);
},
onAnswer: function(answer) {
console.log(answer);
}
});
var Cat = Class(function() {
this.listen('call', this.onCall);
}, {
Encapsulate: Observer,
onCall: function(initiator) {
initiator.trigger('answer', 'Meow! :P');
}
});
var human = new Human();
var cat = new Cat();
human.callCat(cat);
Links