Skip to content

Instantly share code, notes, and snippets.

@wookiehangover
Created November 19, 2012 21:48
Show Gist options
  • Save wookiehangover/4114251 to your computer and use it in GitHub Desktop.
Save wookiehangover/4114251 to your computer and use it in GitHub Desktop.
Model = function(){
this.events = $({});
this.attributes = {};
};
Model.prototype.set = function( key, value ){
var self = this;
var events = [];
var cached_attributes = _.extend( {}, this.attributes );
if( _.isObject( key ) ){
_.each(key, function(v,k){
self.attributes[k] = v;
events.push({ key: k, value: v });
});
}
if( key !== undefined && value !== undefined ){
this.attributes[key] = value;
events.push({ key: key, value: value });
}
var new_attributes = _.extend( {}, this.attributes );
// trigger `change` events for the entire model and individual keys
if( events.length ){
this.events.trigger('change', [new_attributes]);
if( self.collection ){
self.collection.events.trigger('change', [ self, new_attributes ]);
}
_.each(events, function(event){
if( cached_attributes[event.key] !== event.value ){
self.events.trigger('change:'+ event.key,
[event.value, cached_attributes[event.key]]);
if( self.collection ){
self.collection.events.trigger('change:'+ event.key,
[ self, event.value, cached_attributes[event.key] ]);
}
}
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment