How to retrieve a collection which is inside another collection in Backbone - backbone.js

I have a collection of the following structure:
[ {Object1} {Object2} ]
Now Object1 = { CollectionA : [{}, {}]} and Object2 = { CollectionB: [{}, {}]
How do I access CollectionA or CollectionB?

You can access them in following way:
collection
.at(0) //get first element in collection
.get('CollectionA') //get CollectionA property
You can also find a model with CollectionA property by using collection.get and passing model's id.

Related

backbone collection contains no models even though the models were already created

I'm really confused about something regarding collections and models in backbone. Since I'm learning backbone, I haven't been able to fully understand it. I'm working on a backbone project that displays the question with branching logic; the next question that appears is based on the answer to the current question. I created a collection and model that stores (if this is the proper terminology) the response which is then retrieved in a separate view (an email form view) where these responses are added to the message box. Here's my collection to the response.
App.Collections.ResponseCollection = Backbone.Collection.extend({
model: App.Models.ResponseModel
});
and this is the model:
App.Models.ResponseModel = Backbone.Model.extend({
idAttribute: "_id",
defaults: {
response: '',
answer: ''
}
});
which is created like this:
saveResponse: function (qModel, option) {
var qid = qModel.get('question_id');
var mod = this.response.find(function (model1) {
return model1.get('_id') == qModel.get('question_id');
});
if (typeof (mod) == "undefined") {
var responseModel = new App.Models.ResponseModel({
_id: qModel.get('question_id'),
response: qModel.get('question'),
answer: option
});
this.response.add(responseModel);
}
else {
mod.set('answer', option);
}
},
In the view which displays the questions, I instantiated the model and added the response to it which is then added to the collection. This works fine - the responses are added to the model and also it is added to the collection. Now, I want to retrieve this collection and fetch the response from each model so that it's added in the textarea. So, this is what I did in the email view..
var options = new App.Collections.ResponseCollection();
But when I print the collection in console, this is what I see - there's no model in the collection
child {length: 0, models: Array[0], _byId: Object, constructor: function, model: function…}
These data are not saved and retrieved from the database. These responses are added to the model only to retrieve it later to be added to the email form.
I'm confused why it doesn't show me any models in the collection

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.

pulling in a collection with backbone.js

I am trying to pull in a collection from the url attribute and am having some problems. It seems fetch() returns successfully, but then I cannot access the models in my collection with get(). I am using bbb and requireJS to develop my modules
var rooms = new Rooms.Collection(); // calls the rooms module
rooms.fetch({success: function(){
console.log(rooms.get(1)); // should output the first model
});
Here is my collection code in the rooms module:
Rooms.Collection = Backbone.Collection.extend({
model: Rooms.Model,
url: 'http://localhost:8888/projects/meeting-room/app/data/rooms.json'
});
If I output rooms, everything turns out fine. But when I try for a specific model, that is when I get an error.
[{
"id": 12345,
"name": "Ford",
"occupied": false
},
{
"id": 23458,
"name": "Chevy",
"occupied": false
},
{
"id": 83565,
"name": "Honda",
"occupied": false
}]
The collection.get method looks up a model by id. If you want to find a model by position, use collection.at instead.
Also notice that array indices in javascript are 0-based, so the first model can be found with:
var model = collection.at(0);
For convenience, Backbone collections also implement some of underscore's array and collection methods, including first. That means you can also find the first model with:
var model = collection.first();

Search collection and retrieve model backbonejs

I am trying to search a collection for a model attribute and then grab and return the entire model ?
var myModel = Backbone.Model.extend({
defaults: {
a: '',
b: '',
c: '',
d: '',
e: ''
}
});
My collection has around 100 of myModels.
I am trying to search through the collection by a, find it and then return the entire myModel of a so I can access the other attributes ?
If I understand your question correctly, you want to use the where method on Backbone collections, here in the docs:
http://backbonejs.org/#Collection-where
So, given an instance of MyCollection called myCollection that has MyModels in it, you can say:
var foundModels = myCollection.where({a:'some value'});
and foundModels will contain an array of the models you seek
BTW, if you are doing a more complex search, use the filter method instead, passing a function as the first argument that returns true on the desired match:
var modelsWhoseAStartsWithA = myCollection.filter(function(anyModel) {
var startsWithA = new RegExp(/^[aA]/);
return startsWithA.test(anyModel.get('a'));
});

backbone.js: how can I partially update the model json object using .set()?

My backbone.js model has a json object in defaults like this:
test: {
testArr: [{
obj1: value1,
obj2: value2
}]
}
How can I update just a part of the model for eg: test.testArr[0].obj1 using this.model.set()?
You'll need to extract the array from the properties, update it, and inject it back in. Assuming your model is called model, that would look like:
var newTestArr = model.get('testArr');
newTestArr.obj1 = 'foobar';
model.set({testArr: newTestArr});

Resources