Cristiano Fontes
Cristiano Fontes

Reputation: 5088

Setter in Javascript + BackBone is this the right way?

I got this "object"

Person = Backbone.Model.extend({
    defaults: {
        name: 'Fetus',
        age: 0,
        children: []
    },
    initialize: function() {
        this.bind("change:name", function() {
            var name = this.get("name");
            alert("Changed my name to " + name);
        });
    },
    adopt: function(newChildsName) {
        this.get("children").push(newChildsName);
    },
    setName: function(name) {
        this.set({
            name: name
        });
    }
});

Can't the set method setName be done like this : I tried but they don't work

setName: function(name){
  this.get(name) = name;
}

or

setName: function(name){
  this[name].set(name);
}

Is there another way ? I can't go around thinking the original way is too ugly to use.

Upvotes: 0

Views: 189

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

For clarity I am changing the argument name to newName. While:

this.set({name: newName});

means: set a value of an attribute named name with new value of newName parameter (correct), this form:

setName: function(newName){
  this.get(newName) = newName;
}

does nothing. It gets an attribute whose name is provided in newName parameter and returns it. The assignment has no effect.

On the other hand this:

setName: function(newName){
  this[newName].set(newName);
}

will probably throw an error. this is a Backbone model object. It contains attributes property, so probably:

this.attributes[newName] = newName;

is more reasonable (change the attribute whose name is passed in newName parameter to newName value. However in this case the change event won't be triggered. But let me guess, this is what you really wanted:

setAttr: function(name, value){
  var diff = {};
  diff[name] = value;
  this.set(diff);
}

In this case you can call:

model.setAttr('id', 7);

Which is equivalent to:

model.setAttr({id: 7});

and triggers change:id correctly.

Upvotes: 3

Eric Turner
Eric Turner

Reputation: 1824

The original way looks best to me. You MUST call set() on the model for Backbone's event system to work properly. Your two examples don't make much sense (i.e. assigning a value to a value, and calling set() on a value instead of on the model.)

I actually think adding your own setName method is kind of odd. Anyone programming Backbone.js should know to use the built-in set() function on model instances to set property values.

Upvotes: 1

Related Questions