Created
February 9, 2012 14:37
-
-
Save robinduckett/1780350 to your computer and use it in GitHub Desktop.
Backbone.CompatModel
This file contains 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
Backbone.CompatModel = function(attributes, options) { | |
var defaults; | |
attributes || (attributes = {}); | |
if (options && options.parse) attributes = this.parse(attributes); | |
if (defaults = getValue(this, 'defaults')) { | |
attributes = _.extend({}, defaults, attributes); | |
} | |
if (options && options.collection) this.collection = options.collection; | |
this.attributes = {}; | |
this._escapedAttributes = {}; | |
this.cid = _.uniqueId('c'); | |
this.set(attributes, {silent: true}); | |
delete this._changed; | |
this._previousAttributes = _.clone(this.attributes); | |
this.initialize.apply(this, arguments); | |
}; | |
_.extend(Backbone.CompatModel.prototype, Backbone.Model.prototype, { | |
set: function(key, value, options) { | |
var attrs, attr, val; | |
if (_.isObject(key) || key == null) { | |
attrs = key; | |
options = value; | |
} else { | |
attrs = {}; | |
attrs[key] = value; | |
} | |
// Extract attributes and options. | |
options || (options = {}); | |
if (!attrs) return this; | |
if (attrs instanceof Backbone.Model) attrs = attrs.attributes; | |
if (options.unset) for (attr in attrs) attrs[attr] = void 0; | |
if (typeof options === "undefined" || options.mute !== true) { | |
Backbone.Model.prototype.set.apply(this, [attrs, options]); | |
} else { | |
this.setMuted.apply(this, [attrs, options]); | |
} | |
}, | |
setMuted: function(attrs, options) { | |
var now = this.attributes, escaped = this._escapedAttributes; | |
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; | |
for (var attr in attrs) { | |
var val = attrs[attr]; | |
if (!_.isEqual(now[attr], val)) { | |
now[attr] = val; | |
delete escaped[attr]; | |
} | |
} | |
return this; | |
}, | |
}); | |
Backbone.CompatModel.extend = Backbone.Model.extend; | |
var getValue = function(object, prop) { | |
if (!(object && object[prop])) return null; | |
return _.isFunction(object[prop]) ? object[prop]() : object[prop]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment