Using Composite Views with Backbone Marionette and Relational - backbone.js

I've been using Marionette for a couple of weeks and just discovered Backbone Relational so I'm trying to figure out how to integrate the two. Ideally, I would like to use a composite view to render data that is structured like this where each 'item' has its own item view:
list : {
name : 'List 1',
items : [
item1 : {
name : 'Item 1',
id : 1
},
item2 : { ... }
item3 : { ... }
]
}
Normally with composite views you need to have a collection of models that it will iterate through to render each item. With relational, I've just got one model (the list) and that model has a collection (items) within it. Is it possible to render this out using Marionette's views or do I need to use a plain Backbone view and handle the rendering and iteration myself?

This is quite common, and easy to do. In your CompositeView definition, you can specify the collection to use in the initialize method.
Backbone.Marionette.CompositeView.extend({
// ...
initialize: function(){
this.collection = this.model.get("childcollection");
}
});

Related

Backbone Collection Set method remove existing elements and then add all elements

I have a backbone collection.I want to add or remove some models dynamically in the collection. But if i am using collection.set() method then it is going to remove first all elements and then it will add all elements again.
What i want to do is trigger add event of collection for those whose are really new added and trigger remove events for those whose are removed from previous collection.
Here is a example [http://jsfiddle.net/PkJCx/2/]
From the docs
The set method performs a "smart" update of the collection with the
passed list of models. If a model in the list isn't yet in the
collection it will be added; if the model is already in the collection
its attributes will be merged; and if the collection contains any
models that aren't present in the list, they'll be removed.
It is also a good idea to provide `idAttribute' to the model so that the collection identifies that based on the id. Otherwise the collection would not know if the model is a new one or not.
So after setting the id and using set, you can see that is performs a smart update
$(function () {
var MyModel = Backbone.Model.extend({
// This attribute should be set as a default
defaults: {
Name: ''
},
// Set the id attribute so that the collection
// know that it is the old model
idAttribute: 'id'
});
var Coll = Backbone.Collection.extend({
model: MyModel
});
var models = [{
Name: 'A',
id: 1
}, {
Name: 'B',
id: 2
}];
var collection = new Coll(models);
collection.bind('add', function (model) {
alert('addb')
});
collection.bind('remove', function () {
alert('add')
});
models = [{
Name: 'A',
id :1
}, {
Name: 'B',
id: 2
}, {
Name: 'C',
id: 3
}];
collection.add(models);
});
Check Fiddle
It will not try to remove the other 2, but Backbone is smart enough to identify that 2 of them are old models and then just merges the newer one into the collection.

Fire a remove event on fetching a collection

This is an odd behavior I think. I have two "section" instances. Each one with an exercises collection. Then, I do a fetch for each collection and here is the problem. From server can I to receive some model that can be in the two collections at the same time. But this wouldn't be a problem because they are independent instances.
Model:
class App.Models.Section extends Backbone.RelationalModel
relations: [
{
type: Backbone.HasMany
key: 'exercises'
relatedModel: 'App.Models.Exercise'
collectionType: 'App.Collections.Exercises'
reverseRelation:
key: 'section'
includeInJSON: false
}
]
View:
class App.Views.Section extends Backbone.Views
initialize: ->
#collection.bind 'add', #renderExercise
#collection.bind 'remove', #unrenderExercise
#subviews = {}
renderExercise: (exercise) =>
view = new Baskeitor.Views.ExerciseShow model: exercise
#subviews{exercise.cid} = view
#$el.append view.render().el
unrenderExercise: (exercise) =>
#subviews{exercise.cid}.remove()
delete #subviews{exercise.cid}
Two instances:
section1 = new App.Models.Section
section2 = new App.Models.Section
Fetch in the two exercises collection:
section1.get('exercises').fetch({ data: params, remove:false })
section2.get('exercises').fetch({ data: params, remove:false })
I lied, this is my problem with Backbone. In a first time the collections receive their models and I generated a view for each model (an event 'add', so I render the exercise view). But next, for some reason than I don't understand, Backbone trigger a remove event and removes all models repeated. In resume, only I can have in the collections whose models aren't in the other.
EDIT
I have identified the problem. The matter is that ids are duplicates. If I change their ids manually, then all works fine. But otherwise it doesn't do it. But I think this don't have sense because I am instanciating two differents sections. Each section would have its own array with the ids of exercises.
Finally I have just remove Backbone-Relational from my project.

How to store a reference to a Collection in a Model in Backbone.js?

When creating new collection (Choices) I want to set a property on it (ex: _question) which links back to the containing Model (MultipleChoiceQuestion)
This took me quite a bit of time to figure out, so in case somebody in the future has this problems...here's the code I ended up writing.
I discovered, unlike Model, Collection's initialize() function accepts 2 parameters. The first is models (which is a list of models you can initialize the collection with). The second is options (what you want). For a while my Collection started out with 1 model inside and I couldn't figure out why. Turns out I was passing my options into the models field.
THE CONTAINING MODEL:
m.MultipleChoiceQuestion = Backbone.Model.extend({
initialize: function(){
//NULL as first parameter because we don't want models
this.choices = new c.Choices(null, {
_question: this //this is referring to current question
}); //choices Collection is this
}
});
THE COLLECTION
c.Choices = Backbone.Collection.extend({
initialize: function(models, options){
this._question = options._question;
},
model: m.Choice
});
I actually found that although my 1st answer technically works, there's a plugin that makes care of storing collections in models (and creating appropriate One->Many, One->One and Many->One relationships
https://github.com/PaulUithol/Backbone-relational
Using that plugin you store the parent question as an ATTRIBUTE
m.MultipleChoiceQuestion = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'choices', //says to store the collection in the choices attribute
relatedModel: m.Choice, //knows we are talking about the choices models
includeInJSON: true, //when we do toJSON() on the Question we want to show serialize the choices fully
reverseRelation: {
key: 'question', //in the CHOICE object there will be an attribute called question which contains a reference to the question
includeInJSON: false //when we do .toJSON on a CHOICE we don't want to show the question object (or maybe we want to show the ID property in which case we set it to "id")
}
}],
coolFunction: function () {
this.get('choices').each(function(choice){
choice.doSomethingChoicey();
});
}
});
So now if we are in the choices model we can fully reference anything in the parent question:
m.Choice = m.RelationalModel.extend({
coolFunction: function(){
this.get('question').doSomemethingQuestiony();
var question_numer = this.get('question').get('question_number');
}
});

Backbone sorting procedure. UI vs Data

My question is about the proper way to show a list of records using backbone. Lets say you have a person model that you want to display to the user and allow them to sort by first name, last name, id....
The first instinct is to just have the view catch the event and re-render based on the users sort option. The problem with this method is that it is U.I. driven and not data driven.
Second thoughts are to set the sorting attributes in the model since the collection does not contain attributes (though that seems would be the best option). This method is at least data driven by setting the sorting attributes but is horribly redundant and if the sorting attributes are not stripped out on save they are sent to the server | local or...
Last thought is probably the correct one. Create a second model that would be a control model used contain sorting/displaying properties. My issues with this method is events and models can get very unruly. If you expand beyond just a person model and make this a fairly large app you have a LOT of models and events and gets hard to manage. The model-1 view has to catch the initial event, then have the collection trigger a custom event then the second model has to catch the custom event and render it.
Sorry for the long post, I am fairly new to backbone js and want to make sure I have the best practice grasp. Thanks in advance for the help. I hope I am at least on the correct track.
I just implemented this last night.
You can set a new collection comparator and then use the sort method on the collection. sort will fire a reset event, which you can use in your view to re-render the list.
Here is my view, which contains a select box that allows the user to choose how to sort the data:
App.HouseListView = Backbone.View.extend({
el: '.house-list',
initialize: function() {
App.houseCollection.bind('reset', this.populateList, this);
},
events: {
'change .sort':'sort',
},
populateList: function(collection) {
this.$('ul').html('');
_.each(collection.models, function(model) {
var view = new App.HouseListElemView({model:model});
this.$('ul').append(view.el);
});
},
sort: function(e) {
var sort_by = $(e.srcElement.selectedOptions[0]).attr('data-sort-by');
App.houseCollection.comparator = function(house) {
return house.get(sort_by);
}
App.houseCollection.sort();
},
});
Hope this helps
EDIT: Implemented #mu is too short's suggestion:
App.Houses = Backbone.Collection.extend({
model: App.House,
url: API_URL,
_sort_by: 'price',
sort_houses_by: function(sort_by) {
this._sort_by = sort_by;
this.sort();
},
comparator: function(house) {
return house.get(this._sort_by);
},
});
App.houseCollection = new App.Houses();
App.HouseListView = Backbone.View.extend({
el: '.house-list',
initialize: function() {
App.houseCollection.bind('reset', this.populateList, this);
},
events: {
'change .sort':'sort',
},
populateList: function(collection) {
this.$('ul').html('');
_.each(collection.models, function(model) {
var view = new App.HouseListElemView({model:model});
this.$('ul').append(view.el);
});
},
sort: function(e) {
var sort_by = $(e.srcElement.selectedOptions[0]).data('sort-by');
App.houseCollection.sort_houses_by(sort_by);
},
});

backbone.js: define an initial set of models when creating a collection

I'm creating a backbone view for displaying a list of folders created by user in my webapp. but I want to have a default entry like no folder to be displayed in the list as well.
Instead of inserting the DOM inside the view, I want to just add a model to the collection which does not get synced to server but is just used to be rendered in the view.
Is there a way I can do this? I tried this an failed...
var def = {'name': 'none', 'selected': 'true'};
var coll = new app([def]);
// model here
var appitem = Backbone.Model.extend({
defaults: {
name: '',
id: '',
selected: 'false'
}
});
// collection here
app = Backbone.Collection.extend({
model: appitem,
url: '/apps'
});
You should not alter your models based on what the view needs.
If you need to display a 'no folder' entry, than it belongs in the view.
Don't complicate your life by adding data without meaning to the model layer. Keep it in the view.

Resources