Backbone models .get()
and .set()
routines are fine if your values are simple attributes. I have inherited an app however where the values are also JSON objects.
i.e. model.get("key")
returns
{start:
{top:5, bottom:6},
end:{...}
}
etc. Setting any of these values using .set()
is a PITA because you have to pull out the old value, make the change you want, and punt it back in again. i.e. if I want bottom
= 7, you can't just do .set("start.bottom",7)
. I need to do something like:
var tempValue = model.get("start");
tempValue.bottom = 7;
model.set("start",tempValue)
Models have an attributes property, where you can do model.attributes.start.bottom = 7
. Now this presumably doesn't fire any event handlers, because looking at the Backbone code, that is done in set
.
So two questions:
- If I don't need the change handlers to fire, is there anything wrong with setting attributes directly.
- Is there anyway of firing the change handlers manually after setting attributes?
The Backbone changelog says - "The Model#change method has been removed, as delayed attribute changes are no longer available" -but I'm not entirely sure why this would be. It sounds useful.
Related to this: I'm also trying to parse a HTML form into the model. I've been trying to use ModelBinder, but it can't handle nested JSON. e.g. <input type="text" name="start.top">
Edit:
I've just realised you can do model.set({})
with an object. e.g. model.set({start :{top:7}});
but it's a bit clunky