Many to many relationship events with backbone.js

716 views Asked by At

I have a many-to-many relationship with two of my backbone.js models implemented using a pivot table on the serverside. I'm trying to figure out how to structure it clientside. My current structure is:
1) I have a Tag model, and a TagView which renders a checkbox and the tag label, I have a checked event on the checkbox which does nothing at the moment.

  • I have a TagsCollection, which holds a bunch of Tags.
  • I have a TagsCollectionView, which binds add, reset etc of the TagsCollection, and adds TagViews for the added Tags, renders them, and appends the html to its current html (on reset, the html is reset).
  • I have a global TagCollection instance which contains all the possible tags
  • I have a Notes Model which contains an (empty) TagCollection called selectedtags on init.
  • The server returns an array of selected tagids for each Notes, which I add to its TagCollection.
  • Now comes the hard part, tying it all together.. my NotesView has its own TagsCollectionView which is bound to the global TagsCollection (so it can list all the Tags).. now, how do I get a checked event on the checkedbox of its sub TagViews to trigger an add to this Notes model's selectedtags? Should I provide a reference to the this Notes model instance to the TagsCollectionView on init which then provides it to all the TagViews it creates, whose checked event then adds/removes items from that model? That's the best way I can figure out how to do this, any other thoughts would be appreciated.
1

There are 1 answers

2
Umesh Patil On

View is only for visual display of model. Please specify the need for TagsCollectionView in more details:

  1. Use change event for checking the checkbox.
  2. I would advise incremental coding. First work with the Tag and TagView, As it works, continue adding collection to hold the Tags. After that you can add Notes. It's a 'divide and conquer' :)
  3. Don't confuse with the whole design, it is very simple when you start.

I can not provide the whole design due to lack of requirement details. but, I think below code should trigger the starting point of your design.

var TagsCollectionView=Backbone.View.extend({
 el:$(), 
});

var Tag=Backbone.Model.extend({
  defaults:{
   // define the default properties
  }
});

var TagView=Backbone.View.extend({
  el:$("body"),
  events:{
   'change #checkBox':'customFunction'
  },
  initialize: function(){
   _.bindAll(this, 'render','customFunction');
   this.render();   
  },  
  render:function(){
   var tag=new Tag();
   // code to render the checkbox and label
  },
  customFunction:function(){
   // whatever you want to do after checking event of checkbox
  }
});

// collection to collect all the tags
var TagCollection=Backbone.Collection.extend({
  model:Tag
});

var Notes=Backbone.Model.extend({
  defaults:{
   'tagCollection':TagCollection
  }
});

// you do not require TagsCollectionView