2

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

Mark
  • 1,754
  • 3
  • 26
  • 43

1 Answers1

2
  1. If I don't need the change handlers to fire, is there anything wrong with setting attributes directly.

I think that this may answer your question: Backbone.js get and set nested object attribute

  1. Is there anyway of firing the change handlers manually after setting attributes?

The set method (without silent option) triggers 2 events: "change" and "change:attributeName".

If you need it, you can trigger them manually by invoking:

model.trigger("change change:attributeName")
Community
  • 1
  • 1