Skip to content

Instantly share code, notes, and snippets.

@k33g
Created August 6, 2011 06:41
Show Gist options
  • Save k33g/1129087 to your computer and use it in GitHub Desktop.
Save k33g/1129087 to your computer and use it in GitHub Desktop.
add Properties (get set) to BackBone Models
window.BBExtModel = Backbone.Model.extend({
initialize : function() {
function defineProperty(o,p) {
Object.defineProperty(o,p,{
get : function() { return o.get(p);},
set : function(value) {
var v = {}; v[p] = value;
o.set(v);
},
enumerable: true,
configurable: true
});
};
var m;
for(m in this.attributes){
defineProperty(this, m);
}
}
});
window.Human = BBExtModel.extend({});
window.Animal = BBExtModel.extend({
initialize: function Animal() {
BBExtModel.prototype.initialize.call(this);
console.log('doing something');
}
});
var bob = new Human({firstName:'Bob', lastName:'Morane'});
var wolf = new Animal({name:'WOLF'});
/*
Now :
bob.firstName is equivalent to bob.get('firstName')
bob.firstName = "BOBBY" is equivalent to bob.set({firstName : 'BOBBY'})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment