3.3. The Observer Pattern (ok)
Last updated
Last updated
C:\xampp\htdocs\php\js\main.js
require(['observer/init'],function(init) {
var examples = {
observer: init
}
for (var example in examples) {
examples[example].init();
}
});
C:\xampp\htdocs\php\js\observer\init.js
define(function(require) {
'use strict';
return {
init: function() {
var subject, observer, otherObserver, data, moreData;
var Subject = require('observer/subject');
var Observer = require('observer/observer');
subject = new Subject();
observer = new Observer('observer1');
otherObserver = new Observer('observer2');
data = {
prop: 'something'
};
moreData = {
prop: 'something else'
};
subject.observe(observer);
subject.observe(otherObserver);
subject.add(data);
subject.add(moreData);
subject.unObserve(observer);
subject.remove(data);
}
};
});
C:\xampp\htdocs\php\js\observer\subject.js
define(function(require) {
'use strict';
var Observers = require('observer/observers');
var Collection = function(items) {
this.observers = new Observers();
this.collection = items || [];
};
Collection.prototype.observe = function(observer) {
this.observers.add(observer);
};
Collection.prototype.unObserve = function(observer) {
this.observers.remove(observer);
};
Collection.prototype.notify = function(event, data) {
this.observers.get().forEach(function(observer) {
observer.notify(event, data);
});
};
Collection.prototype.add = function(item) {
this.collection.push(item);
this.notify('added', item);
};
Collection.prototype.remove = function(itemToRemove) {
this.collection = this.collection.filter(function(item) {
if (item !== itemToRemove) {
return true;
}
this.notify('removed', item);
return false;
}, this);
};
return Collection;
});
C:\xampp\htdocs\php\js\observer\observers.js
define(function() {
'use strict';
var Observers = function() {
this.observers = [];
};
Observers.prototype.add = function(observer) {
this.observers.push(observer);
};
Observers.prototype.remove = function(observerToRemove) {
this.observers = this.observers.filter(function(observer) {
return observer !== observerToRemove;
});
};
Observers.prototype.get = function() {
return this.observers;
};
return Observers;
});
C:\xampp\htdocs\php\js\observer\observer.js
define(function() {
'use strict';
var Observer = function(name) {
this.name = name;
};
Observer.prototype.notify = function(event, data) {
console.log('The event was ', '"' + event + '",', 'the data was', data, 'and I am ', this.name);
};
return Observer;
});