Skip to content

Instantly share code, notes, and snippets.

@mikeapr4
Last active June 16, 2017 14:28
Show Gist options
  • Save mikeapr4/b549b76394e2c79e9b54eddcc1a63c19 to your computer and use it in GitHub Desktop.
Save mikeapr4/b549b76394e2c79e9b54eddcc1a63c19 to your computer and use it in GitHub Desktop.
Add reactive properties to a backbone model to allow plain Object manipulation.
var originalSet = Backbone.Model.prototype.set
, noConflictPrefix = '$$';
/**
* During initial construction, a model
* calls set(), but there is also a check
* to ensure the reactivity only occurs on construction
*/
Backbone.Model.prototype.set = function() {
var duringConstruction = (this.changed === null);
var retval = originalSet.apply(this, arguments);
if (duringConstruction) {
_.each(this.attributes, function(val, key) {
var propName = this[key] ? noConflictPrefix + key : key;
Object.defineProperty(this, propName, {
get: this.get.bind(this, key),
set: this.set.bind(this, key)
});
}, this);
}
return retval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment