Skip to content

Instantly share code, notes, and snippets.

@xbill82
Created March 27, 2015 13:36
Show Gist options
  • Save xbill82/bb7ed0967573bb6491b5 to your computer and use it in GitHub Desktop.
Save xbill82/bb7ed0967573bb6491b5 to your computer and use it in GitHub Desktop.
Home-made One-to-many relationship in Backbonejs
define(['require', 'backbone', 'collections/c_tags'], function(require) {
"use strict";
var Backbone = require('backbone');
var TagsCollection = require('collections/c_tags');
return Backbone.Model.extend({
tagsCollection: null,
url: function() {
return 'api/articles/' + this.get('id');
},
initialize: function() {
if (!this.tagsCollection)
this.initializeTagsCollection();
},
initializeTagsCollection: function() {
this.tagsCollection = new TagsCollection();
this.tagsCollection.on('add', function(model, collection, options) {
this.updateTagsAttribute();
}, this);
this.tagsCollection.on('remove', function(model, collection, options) {
this.updateTagsAttribute();
}, this);
this.tagsCollection.on('change', function(model, options) {
this.updateTagsAttribute();
}, this);
},
parse: function(data, options) {
if (!options.parse)
return data;
if (!this.tagsCollection)
this.initializeTagsCollection();
this.tagsCollection.reset();
this.tagsCollection.add(data.tags, {silent: true});
return data;
},
updateTagsAttribute: function() {
this.set('tags', this.tagsCollection.toJSON());
},
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment