Skip to content

Instantly share code, notes, and snippets.

@samuelcole
Created October 26, 2012 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelcole/3960699 to your computer and use it in GitHub Desktop.
Save samuelcole/3960699 to your computer and use it in GitHub Desktop.
function Model(object) {
this.initialize(object);
}
Model.prototype.initialize = function (object) {
this.listeners = {};
this.listeners._global = [];
for (var key in object) {
if (object.hasOwnProperty(key)) {
this.set(key, object[key]);
}
}
};
Model.prototype.set = function (key, value) {
var old_value = this.key;
this[key] = value;
if (value !== old_value) {
this._broadcast(key);
}
return this;
};
Model.prototype.on_change = function (key, callback) {
if (typeof key === 'function') {
this.listeners._global.push(key);
return;
}
if (typeof this.listeners[key] === 'undefined') {
this.listeners[key] = [];
}
this.listeners[key].push(callback);
return this;
};
Model.prototype._broadcast = function (key) {
var x;
if (typeof this.listeners[key] !== 'undefined') {
for (x = 0; x < this.listeners[key].length; x = x + 1) {
this.listeners[key][x].apply(this);
}
}
for (x = 0; x < this.listeners._global.length; x = x + 1) {
this.listeners._global[x].apply(this);
}
};
Model.prototype.extend = function () {
var _this = this;
function fn() {
_this.initialize.apply(this, arguments);
}
fn.prototype = Model.prototype;
return fn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment