Frage

I need to update one attribute of a model after an event has been triggered from the view. I do not know which attribute will have to be updated beforehand. How can I set a variable attribute with backbone's set method?

Here is an example set of attributes for my model:

defaults: { 
            content: 'Stupid filthy Hobbit',
            date: '03-19-14',
            position: [ 
                        {top: 134, left: 22},
                        {top: 78,  left: 24},
                        {top: 91,  left: 18}  
                      ]
          } 

Here is the method I use in the view:

events: {
    'change input': 'onChangePosition'
},

onChangePosition: function(e){

    var key = $(e.currentTarget).data('key');
    var attribute = $(e.currentTarget).data('attribute');
    var value = $(e.currentTarget).val();

    this.model.set(['position'][key][attribute], value);
}
War es hilfreich?

Lösung

I'm assuming that key is the integer index of the object you want to update in the position array? If so, you'll need to get the position array, update it and then set it again. Try this:

var position = this.model.get('position');
position[key][attribute] = value;
this.model.set('position', position);

Just to clarify, the reason why is because Backbone.Model.set() only accepts two forms. Either a hash of attributes to set, or the name of a specific attribute and its value to set. But there is no syntax that would allow you to specify an indexed item of an array, so you have to get the whole thing, update it then set it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top