Skip to content

Instantly share code, notes, and snippets.

@victor-github
Created May 24, 2011 16:33
Show Gist options
  • Save victor-github/989071 to your computer and use it in GitHub Desktop.
Save victor-github/989071 to your computer and use it in GitHub Desktop.
BackboneJS Associations - Document HasMany Categories
var Document = Backbone.Model.extend({
initialize: function() {
var categories = new App.Collections.Categories();
var self = this;
categories.url = function() {
return self.url() + '/categories';
};
self.set({
categories: categories
});
},
validate: function(attrs) {
var errors = { document: {}};
if (attrs.name === "") {
errors.document["name"] = "Name cannot be blank";
}
if (!jQuery.isEmptyObject(errors.document)) {
return errors;
}
},
url: function() {
var base = 'documents';
if (this.isNew()) {
return base;
}
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
},
addCategory: function(category, options) {
var self = this;
options || (options = {});
_.extend(options, {document_id: self.get('id')});
category.save(options,
{
success: function(model,resp) {
self.get('categories').add(category,{silent: true});
},
error: function(model, resp) {
debugger;
new App.Views.Notice({ message: resp});
}
});
},
deleteCategory: function(cat) {
this.categories.remove(cat, {silent: true})
},
//delete categories one by one
deleteAllCategories: function() {
var self = this;
_.each(self.categories, function(el) {
el.destroy({success: function(model, resp) {
self.deleteCategory(el);
}
})
})
},
//this would call addCategory for each
addCategories: function(arrayOfCats) {
},
//this would figure out a way to do the update in a single json request (e.g. by using $.ajax)
addBulkCategories: function(arrayofCats) {
},
//delete all through bulk json update
deleteAllBulkCategories: function() {
}
,toJSON: function() {
json = this.attributes;
return _.extend(json, {categories_attributes: this.get('categories').toJSON()});//TODO: inherit this centrally
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment