In the following DOM event handling example (using jQuery):
$('#shopping-cart').on('click', function(event){...});
could I not call the shopping-cart DOM element the observable, and the function the observer? There is no "general" click event being hooked to, but a click event specific to the shopping-cart object itself.
The javascript example of observable/observer example I'm operating from is the following (taken from here):
// MyFancyObservable.js
var util = require('util');
var EventEmitter = require('events').EventEmitter;
function MyFancyObservable() {
EventEmitter.call(this);
}
util.inherits(MyFancyObservable, EventEmitter);
MyFancyObservable.prototype.hello = function (name) {
this.emit('hello', name);
};
var MyFancyObservable = require('MyFancyObservable');
var observable = new MyFancyObservable();
observable.on('hello', function (name) {
console.log(name);
});
observable.hello('john');
Notice that in the MyFancyObservable example, the on('hello', function)
looks exactly like DOM event registration.
1 Answer 1
The difference lies in the purpose of the Event.
In your Shopping Cart example, the event gets fired in response to a user action.
In an Observable, the event gets fired in response to a state change.
Are they both examples of Event Handling? Yes.
Are they both Observers? No.
Explore related questions
See similar questions with these tags.