Skip to content

Instantly share code, notes, and snippets.

@j0lvera
Created June 26, 2014 18:39
Show Gist options
  • Save j0lvera/56af866c1ea28e5961d4 to your computer and use it in GitHub Desktop.
Save j0lvera/56af866c1ea28e5961d4 to your computer and use it in GitHub Desktop.
Model Class
// Stores items and notifies observers about changes.
//
// ```
// var model = new Model();
// ```
//
// @class Model
var Model = function(attributes) {
this.id = _.uniqueId('model');
this.attributes = attributes || {};
};
// Store properties and values
//
// ```
// model.set({ name: "Juan Olvera", age: 30 });
// // => Model { id: "model1", attributes: Object, get: function, set: function...}
// ```
//
// @param {Object} object containing the model properties and values
// @return {Object} the model.attributes object
Model.prototype.set = function(attrs) {
// check if the attributes are stored inside an `Object`
if (_.isObject(attrs)) {
_.extend(this.attributes, attrs);
// notify that the model has changed
this.change(attrs);
} else {
throw "attrs is not an Object";
}
return this;
};
// Get the value of defined property
//
// ```
// model.get("name")
// // => "Juan Olvera";
// ```
//
// @param {string} name of the property we are looking for
// @return {value}
Model.prototype.get = function(key) {
return this.attributes[key];
};
// Remove a selected model attribute
//
// ```
// model.remove("name");
// ```
// @param {string} property name
Model.prototype.remove = function(attr) {
delete this.attributes[attr];
};
Model.prototype.has = function(attr) {
return this.attributes.hasOwnProperty(attr);
};
Model.prototype.reset = function() {
this.attributes = {};
this.change(this.attributes);
this.trigger(this.id + "reset", this.attributes);
};
Model.prototype.size = function() {
return _.size(this.attributes);
};
Model.prototype.toJSON = function(opts) {
return _.clone(this.attributes);
};
Model.prototype.change = function(attrs) {
this.trigger(this.id + "update", attrs);
};
_.extend(Model.prototype, Events);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment