Saurabh Verma
Saurabh Verma

Reputation: 6738

Update backbone model with new json

Right now, I'm passing json to model like this:

model m = new app.SomeModel(json);

and then using it, which seems fine.

However, now whenever my json changes, I want to pass the new json to the model, without creating a new instance of the model, something like:

m.updateJson(json);

EDIT: Right now I'm doing something like:

m.set(json)

But can we also do something like:

m.set("json_key",json)

So that later on I'll be able to do:

m.get("json_key") 

to get the entire json ?

Upvotes: 0

Views: 1196

Answers (1)

mavarazy
mavarazy

Reputation: 7735

Just use model.set, it will trigger "change" events, and update dependent objects

setmodel.set(attributes, [options]) Set a hash of attributes (one or many) on the model. If any of the attributes change the model's state, a "change" event will be triggered on the model. Change events for specific attributes are also triggered, and you can bind to those as well, for example: change:title, and change:content. You may also pass individual keys and values.

note.set({title: "March 20", content: "In his eyes she eclipses..."});

book.set("title", "A Scandal in Bohemia");

And If you need to trigger "sync" event, after you have updated a model issue model.trigger("sync")

Upvotes: 2

Related Questions