Skip to content

Instantly share code, notes, and snippets.

@martinnormark
Created January 6, 2013 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinnormark/4466460 to your computer and use it in GitHub Desktop.
Save martinnormark/4466460 to your computer and use it in GitHub Desktop.
Backbone Model helpers
(function (Backbone, _) {
Backbone.CollectionModel = Backbone.Model.extend({
constructor: function (attributes, options) {
Backbone.Model.prototype.constructor.apply(this, arguments);
if (this.collections) {
for (var key in this.collections) {
var array = this.get(key) || [];
this.set(key, new this.collections[key](array));
}
}
if (this.postCollectionInitialize) {
this.postCollectionInitialize.apply(this, arguments);
}
},
set: function (attributes, options) {
if (this.collections) {
for (var key in this.collections) {
if (_.has(attributes, key) && this.get(key)) {
this.get(key).reset(attributes[key]);
delete attributes[key];
}
}
}
return Backbone.Model.prototype.set.call(this, attributes, options);
}
});
})(Backbone, _);
(function (Backbone, _) {
Backbone.Helpers = {
parseDates: function (response, dateProperties) {
var ext = {};
_.each(dateProperties, function (propertyName) {
var date = Date.parse(response[propertyName]);
if (date) {
ext[propertyName] = new Date(date);
}
});
return _({}).extend(response, ext);
},
parseDatesOnModel: function (model, dateProperties) {
var ext = {};
_.each(dateProperties, function (propertyName) {
var date = Date.parse(model.get(propertyName));
if (date) {
ext[propertyName] = new Date(date);
}
});
model.set(ext, { silent: true });
}
}
})(Backbone, _);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment