Created
October 26, 2012 18:54
-
-
Save samuelcole/3960699 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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