Observer pattern implementation
npm install node-observerObserver
-------------
This is an observer pattern module
``bash`
npm install node-observer
Main file: app.js
`app.js
"use strict";
var observer = require("node-observer");
var hello = require("./hello");
observer.subscribe(this, "HELLO", function(who, data) {
console.log(data);
});
hello.send();
`
File: hello.js
`hello.js
"use strict";
var observer = require("node-observer");
var Hello = function() { };
Hello.prototype.send = function() {
observer.send(this, "HELLO", "hello world!!!");
};
module.exports = new Hello();
`
Run
`bash`
node app.js
object:object, event:string, callback:function
subscribe event
object:object, event:string
unsubscribe event
object:object, event:string, data:object
send event 'event' with data 'data'
Under client directory there is a browser version of library.
Added script tag in your html file. See the example below.
File index.html
`index.html`
Javascript observer pattern example: see the result in console
File app.js
`app.js`
$(function() {
Observer.subscribe(this, 'HELLO', function(who, data) {
console.log(data);
});
});
File mylib.js
`mylib.js
(function(window) {
var getInstance = function() {
Observer.send(this, 'HELLO', 'Hello world!!!');
};
if (typeof(mylib) === 'undefined') {
window.mylib = getInstance();
} else {
console.log('mylib already defined.');
}
})(window);
`