Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update model in collection?

Tags:

backbone.js

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

like image 446
jewelwast Avatar asked Mar 18 '13 19:03

jewelwast


3 Answers

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.

like image 151
Prostakov Avatar answered Nov 11 '22 11:11

Prostakov


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. :)

like image 8
tekHedd Avatar answered Nov 11 '22 11:11

tekHedd


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.

like image 2
neebz Avatar answered Nov 11 '22 10:11

neebz