Created
March 27, 2015 13:36
-
-
Save xbill82/bb7ed0967573bb6491b5 to your computer and use it in GitHub Desktop.
Home-made One-to-many relationship in Backbonejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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