Infiinite nested collections in Backbone - javascript

I have a very simple Backbone example:
var myModel = Backbone.Model.extend();
var collection = Backbone.Collection.extend({
model: myModel,
});
var c = new collection([
{first_name: 'a',
last_name:'b'
},
{first_name:'c',
last_name:'d'
}
]);
console.log('c is');
console.log(c);
You can see jsfiddle here.
When you view this in Chrome developer tools, you can see there is a collection attribute on each Backbone model, which you can expand and go into again, infintely. See the image:
What is this? Why does it appear like that?

Inside every model there is a collection object stored if it is part of a collection. What is happening here is you are viewing collection in console and inside it there are two models. Each model has collection object stored in it (which is the same collection which you are viewing). So, it seems like sort of recursion when viewing in console
This is currently not documented in backbone js. See https://github.com/jashkenas/backbone/issues/1161 for more info.

Related

Prevent Backbone collection reset

I am new to Backbone. I see this in every backbone app:
var List = Backbone.collection.extend({
model: model
});
var myList = new List();
I am a bit confused about this. This script is included in a page, and when the page is reloaded or opened again and again, it will keep instantiate new collection doesn't it?
Whenever I save some models into this collection, things are still fine. But when I start to reload the page or open the page again, it will instantiate new collection with the same name again and the collection becomes empty again.
Any suggestions to prevent this? I want collection keep the models even if reloaded.
Use myList.fetch() in your view to load data from your api resource.
Some more info at BB site
Edit:
You can save model by using Collection create
So first instantiate new collection, then use
Collection.create({
name: 'John'
});
You can observe your network log to see what was posted to the api.
For your example:
var List = Backbone.collection.extend({
model: model
});
var myList = new List();
myList.create({
name: 'John'
});

Backbone.js removing the model

I have been trying for hours now, without luck. If you could see on the image, I have mildly complex model. Image is taken from Chrome in debug.
I need to delete a model from collection, also I need to be able to change the URL where the backbone will shoot its ajax for delete. So in essence, this is my model structure:
attributes:
favorites {
bookmarkedArticles: [{id: 123123},{id: ...}],
bookedmarkedSearches: [{}],
dispatchesMailds: []
}
How can I delete model in bookmarkedArticles with id of 123123?
I have tried this:
var model = new metaModel(
{
favourites: {
bookmarkedArticles: {
id: "123123"
}
}
}
);
model.destroy();
also this
aamodel.headerData.collection.remove(model);
No success at all.
The information provided is not giving a lot of details, but I will try to answer considering two scenarios:
Option A:
You are trying to delete a model in the collection that has bookmarkedArticle.id="123123". if that is the case and considering the bookmarkedArticles it is just an Array of objects, I would suggest to filter the Collection using the underscore method filter and then delete the models returned by the filter.
var id = 123123;
var modelsToDelete = aamodel.headerData.collection.filter(function(model){
// find in the bookmarked articles
return _.find(model.get('bookmarkedArticles'), function(ba){
return (ba.id === id);
});
});
_.each(modelsToDelete, function(model){
model.destroy();
});
Option 2: If you want to remove the bookmarked article '123123' associated to your main model using just the 'destroy' method, firstable you have to convert 'bookmarkedArticles' to a Backbone.Collection as it is just an Array of Objects, there are some utilities for Backbone that allows you to do this easily:
https://github.com/blittle/backbone-nested-models
But by default this is not possible, then, If you want to remove the 'bookmarkedArticle' you can create the Backbone.Model and then use the method destroy. Example:
var BookmarkedArticle = Backbone.Model.extend({
url: function(){
return '/bookmarkArticle/' + this.id;
}
});
new BookmarkedArticle({"id": "123123","master": "5",...}).destroy();
Hope this information is useful and provide some guidance to solve your problem.

Get entire model in Backbone JS

In backbone javascript models, we get individual items as shown below:
var type = this.model.get("type");
Here, type will be defined in server side & then fetched in JS using above syntax.
My question is how do I get the entire model in one shot?
I tried this.model.toString() but it prints [object object]
Any suggestion?
EDIT: I'm using above line of code in backbone view & not the model. And in this view, I need to read all the models data even if its JSON string, thts fine with me. How do I get it. I don't want to use separate collection or anything else. I need to update the above view only to get entire model.
You can use model.toJSON() to get all the attributes of a model.
you use a collection
http://backbonejs.org/#Collection
You can then iterate though the collection to obtain each model.
var Library = Backbone.Collection.extend({
model: Book
});
for example and then
books = new Library();
books.each(function(book) {
book.publish();
});
to iterate

Newly saved Backbone model does not appear in collection after fetch

I am using backbone local storage and experiencing some weird behavior.
I have a Model and Collection that is defined, instantiated, and fetched:
MyModel = Backbone.Model.extend({
localStorage: new LocalStore('example-myModels')
//note: LocalStore = Backbone.LocalStore -> https://github.com/jeromegn/Backbone.localStorage
});
MyCollection = Backbone.Collection.extend({
model : MyModel,
localStorage: new LocalStore('example-myModels')
});
var myCollection = new MyCollection();
myCollection.fetch(...);
This collection is then displayed as a list to the user. The user is able to "add" an item to the collection which eventually results in this code:
var newModel = new MyModel();
newModel.save(newModelAttributes, {
success: function(newlySavedModel) {
myCollection.add(newlySavedModel);
}
);
At this point myCollection has the newly added model and I can see the record successfully created in my localStorage database:
Pre-save LocalStorage:
Post-save LocalStorage:
The next step after the user adds the record is to go back to the list, at which point the collection is fetched again:
myCollection.fetch();
Now myCollection no longer contains the new record. No matter how many times I fetch, the new record will not be retrieved - even though I can see it in my localStorage database. I have also tried creating a new instance of the Collection and fetching that but it yields the same results. If I reload the browser, the new record appears as expected. Anyone have any idea what is going on? I get the feeling I am missing something fundamental here...
A running example that reproduces the issue is available here: http://jsbin.com/iyorax/2/edit (make sure the console is visible and click "Run with JS")
Thanks in advance!
Your model and your collection need to share a reference to the same instance of LocalStore, whereas right now you are creating two different objects. To fix this, create the LocalStore object outside of either model or collection, and pass in a reference to it in the constructors of your Model and collection.
I have an application working with Backbone.localstorage and what works for me is I first add the model to the collection and then I call save to the model. like this.
var newModel = new MyModel();
myCollection.add(newModel)
newModel.save();
Im not 100% sure, but my reasoning is that, your model is saved, but your collection is not, and perhaps an index is not being updated and at the time that you call fetch you are getting the unupdated collection.
Hope that helps.
The only reason I can think of due to which the model is not present in the collection is because of Duplicated ID's
I don't see a IdAttribute defined on the model. That could be a problem sometimes.

How to get/parse data from Backbone.LocalStorage

I am trying to understand how Backbone.LocalStorage is used the from the following jagin/todos.
Referring to the Backbone.Marionette doc, In order to render the list of todos, it should be enough to make the following code:
new CompositeView({
model: someModel,
collection: someCollection,
itemView: RowView
});
So, referring to the jagin/todos the collection should be an object fetched from the backbone.localstorage.
My question is:
I would like to get this collection/models from the javascript console.
I did try the following but it returns an object which is different from a backbone.collection.
new Backbone.LocalStorage("todos-marionette");
// {"name":"todos-marionette","records":["1244f588-be3d-c493-5c86-b2abb997af82"]}
Any ideas?

Categories