Last active
June 16, 2017 14:28
-
-
Save mikeapr4/b549b76394e2c79e9b54eddcc1a63c19 to your computer and use it in GitHub Desktop.
Add reactive properties to a backbone model to allow plain Object manipulation.
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
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