backbone model toJSON strangely cache itself - backbone.js

I am still new to backbone:
Here is my problem that I find hard to explain:
on initialisation there is a model something like this:
Model:
{
Id:xxx,
Questions:
[
{
Id: "yy",
Selections:
[
{OptionId:"aaa"},
...,
{OptionId:"zzz"}
]
},
....
]
}
there is a event method updates Selections Collection.
After event triggers I got two different result by with two code below:
window.pkg.Questions.get(this.Id).Selections.reset(selectedoptions);
console.log(window.pkg.Questions.get(this.Id).Selections.toJSON());
console.log(window.pkg.Questions.get(this.Id).toJSON().Selections);
The first log shows the updated model, however the later shows initial default value.
why it is working like this?

They are two different copies. Your QuestionModel has a SelectionsCollection property called Selections, and a Backbone attribute, also called Selections. I assume you want to use the SelectionsCollection, and the attribute will not stay in sync with that. The attribute is the original json which I assume was inadvertently added to the model.
Hard to say exactly how to fix it, because you did not show the code where you create and fetch these models and collections. Wherever you take the Selections JSON and and initially reset it into the collection, you can remove it from the JSON and/or unset it on the QuestionModel if it is already there....
This would also print the wrong, original data:
console.log(window.pkg.Questions.get(this.Id).get('Selections')); // print original JSON
You can remove it in QuestionModel's parse:
parse: function(data) {
// removing Selections from data here will prevent
// it from being added as an attribute.
delete data.Selections;
return data;
}
If you do this, and you want the Selections to be included in the toJSON output of QuestionModel, you would also need to override toJSON.
toJSON: function() {
// get json for Question
var json = Backbone.Model.prototype.toJSON.call(this);
// add updated json for selections
json.Selections = this.Selections.toJSON();
return json;
}

Related

Appending new data to the Backbone Relational Relation

I'm trying to design a load more type of system where every time you press load more you add data to the existing collection. This is a rough sketch of how the UI looks.
Everything works pretty great except as you would except everytime I re-run the
items.fetch
What it does: It overrides the entire collection with the new data
What I want it to do: I want the new records returned to be added to the records collection not override old 'records'
How can I make this work so that the newly fetched records are appended to existing records and not overridden?
Add { remove: false } to your fetch call:
items.fetch({ remove: false, data: { nextId: this.info.get('nextId') } });
What's happening here is Collection#fetch will synchronize its models with the data the server returns. That includes adding new models, updating models already present, and removing models that are not included in the response.
The behavior of fetch can be customized by using the available set options. For example, to fetch a collection, getting an "add" event for every new model, and a "change" event for every changed existing model, without removing anything: collection.fetch({remove: false})
The available set options are add, remove, and merge. Setting one (or all) to false will disable that functionality in the fetch.
It sounds like you just want { remove: false }, leaving the add and merge functionality.
I'm not familiar with backbone-relational,
But with a normal collection, you can do the following in parse method:
Backbone.Collection.extend({
parse: function(response){
// you can update the info here like this.info = response.info or similar
return _.union(this.toJSON(), response.records);
}
});
Basically we combine the response with existing data and return it so that we maintain the previous data when the collection updates

Restangular how to update item in collection

I am currently fiddeling around with restangular and ui-router.
I do resolve a collection of items in my router which makes it available to the underlying controllers. I have a list of todos and i want to edit a todo. So i load a view where i can edit the item.
I get the model by $scope.todo = todos.get(id) I make a change to it and then i do $scope.todo.save() which updates the model on the server. But now i have the old item still in the collection of todos.
I want my collection to reflect the changes in the single item. I could delete the item from the collection and reinsert it afterwards, but this seems a little bit too complicated. Is there no easy way to update a model within a collection?
Update: Adding some Code
Note: The todos property gets resolved if the state is called.
If i edit a single todo i resolve it by
resolve : {
todo : function($stateParams, todos) {
return todos.get($stateParams.id);
}
}
I do some changes and then i call todo.save(). No changes will happen on the collection this way. I tried to do a todos.patch(todo) but that actually did a request to weird url and i guess it is intended to patch the whole collection (?)
I am sure there is a way to change a model within a collection, but i dont know how
After trying some stuff i ended up with replacing the item inside the collection. I created a little helper to lodash which i want to show here:
var replaceItemById = function(list, element) {
var index = _.indexOf(list, _.find(list, { id : element.id }));
list.splice(index, 1 , element);
return list;
};
_.mixin({'replaceItemById' : replaceItemById});
When i want to update a model inside a collection i do step by step:
Fetch the collection
Get a single item from the collection and edit it
Call save on the item
//The server returns the updated model
todo.save().then(function(editedTodo) {
_.replaceItemById(todos, editedTodo);
$state.go('todos.index');
});
This way i do not need to fetch the collection again (even if in most cases this is what you would do) and it is up to date after updating a single item.

Backbone - Using fetched data inside the view

I have fatched the data to Collection variable, but I am not sure what should I do next. How to use this data and to fill the template with it? Here is my code from the render function inside the View.
Collection.url = "../data";
Collection.fetch();
var compiled = _.template(self.data);
self.$el.prepend(compiled(/*MY JSON SHOULD GO HERE*/));
I am a newbie to backbone, so every help is appreaciated.
Here is a Collection definition:
var MainCollection = Backbone.Collection.extend({
model: MainModel,
//localStorage: new Backbone.LocalStorage("kitchen"),
initialize: function (models,options) { }
}), Collection = new MainCollection;
Here is a log of Collection and Collection coverted to JSON:
Assuming Collection is your collection's name (that's pretty confusing I have to say), this is what you're looking for:
self.$el.prepend(compiled(Collection.toJSON()));
Edit:
Don't forget you're fetching the data asynchronously. So when you're evaluating your template, the data hasn't come back yet, and your collection's still empty. Listen to the end of the request ('sync' event I think) or some other events so you know when the collection's populated OR use the success option of the fetch method to specify a callback :)
As for your logs. When you log an object, it will be automatically updated until you check the details. So you logged it while it was empty, but checked it after it was populated (a few ms afterwards).

How to update model in collection?

I have the following Backbone.js collection:
var Tags = Backbone.Collection.extend({
url: "/api/v1/tags/"
}),
How do I update one of the models in the collection so that it posts to /api/v1/tags/id and saves the data for that model.
So if I change name of model with id 2 in the collection
It should PUT to
/api/v1/tags/2 with the following data:
name: new name id: 2
I've also recently wanted to update particular model in the collection. The problem was that if I did use just model.save it didn't update the collection. The goal was to change the model in collection, change it on the server, update collection accordingly and not use the sync method. So for example I have my variable collection and I want to change the model with id = 2. So the first thing, I will create an instance model, like this: var model = collection.get(2)Then I will update the attributes on this particular model:model.set({name: 'new name'})Then I will save it to the server:model.save({}, {url:'/api/v1/tags/'+model.get('id')})Then we have to update collection accordingly to the changes:collection.set({model},{remove: false})set method - it's a 'smart' update of the collection with the list of the models you passed in parameters. remove: false parameter - it's a restriction for a collection to remove existing models in collection. More here.
The first thing you can miss is that in your corresponding Tag model you'll need to set "urlRoot" to match the Collection's "url". Otherwise it doesn't know about the collection at all:
var Tag = Backbone.Model.extend({
urlRoot: "/api/v1/tags"
});
var Tags = Backbone.Collection.Extend({
model: Tag,
url: "/api/v1/tags"
});
This is useful if you want to save the tag separately:
var tag = collection.get(2);
tag.set({key: "something"});
tag.save(); // model.save works because you set "urlRoot"
On the collection, "create()" is also "update()" if id is not null. That's not confusing. :) Therefore, this is pretty much equivalent to the previous sample:
collection.create({id: 2; key: "something"});
This will update the existing tag with id=2 and then trigger a PUT.
This is an ancient question; answering because I was searching for the same answer--you've probably long since solved this problem and moved on. :)
You can pass variables to the save method. It accepts all the options which jQuery's ajax method uses (unless you overrided Backbone.Sync)
You could do something like:
model.save( { name:'new name' } );
The id and PUT method will automatically be added by Backbone for you.

How can i sort after i done the fetch in backone.js

On click of the 'sort by age', i am calling a function to fetch data from server and sort by age value. i do this after i done the fetching, but it result nothing and return all..
any one give a correct way to implement this?
my code:
this code in the view class,
sortByAge:function(){
this.collection.fetch() //fetching new collection
.done(function(data){ // once done i am passing data
var filterType = data.sort('age') // correct way need to sort.
that.collection.reset(filterType); // refreshing the collection
})
},
If before doing a fetch you're already aware that you need collection to be sorted by some specific column, from the docs, we can pass ajax options to the fetch. So fetch might look like this:
this.collection.fetch({
data: {
sort_by: "age"
}
});
sort_by parameter will be available in the server code being executed at the specified url for the collection, so you can return data from the server sorted by sort_by column. And then may be listen to reset event to do some work.
And if you want to sort collection after getting it on the client side may be you can look at these similar questions.
Sorting a Backbone Collection After initialization
Proper way to sort a backbone.js collection on the fly

Resources