Skip to content

Instantly share code, notes, and snippets.

@misantronic
Last active December 3, 2015 11:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misantronic/a369841c817f1a626345 to your computer and use it in GitHub Desktop.
Save misantronic/a369841c817f1a626345 to your computer and use it in GitHub Desktop.
Functional attributes in Backbone
var Model = Backbone.Model.extend({
get: function (attribute) {
var value = Backbone.Model.prototype.get.call(this, attribute);
if(_.isFunction(value)) {
value = value.call(this);
}
return value;
},
toJSON: function () {
var obj = Backbone.Model.prototype.toJSON.apply (this, arguments);
_.mapObject(obj, function (value, key) {
if(_.isFunction(value)) {
obj[key] = value();
}
});
return obj;
}
});
Backbone.sync = function (method, model, options) {
var self = this;
options = options || {};
// Execute function-properties
options.attrs && _.mapObject(options.attrs, function (value, key) {
if(_.isFunction(value)) {
options.attrs[key] = value.call(self);
}
});
return BackboneSync.call(this, method, model, options);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment