Jareish Jareish - 4 months ago 35
Javascript Question

How to set a dynamic property on a model with Backbone.js

I have a lot of properties that needs to be set. Since they have similarities I choose to read out the class the inputbox is part of as property name.

A dynamic property of an object can be set, just like an associative array. So I could do

var customattribute = this.$el.parents('div').attr('id');
var value = $(e.currentTarget()).val();

this.model.attributes[customattribute] = value;

But this wouldn't trigger a change event of the model. I could manually trigger a change event, but this wouldn't update this.model.changedAttributes(), I need to set only the changed attribute, not every attribute.

This of course doesn't work either:

this.model.set(customattribute: value);

So how would I handle this problem?

I have ALOT (200+) attributes that can be set, I wouldn't like to make separate eventlisteners for every attribute unless thats the only way.


var Display = Backbone.View.extend({
className: 'display',
events: {
'slide .slider' : 'sliderHandler'
initialize: function(){
_.bindAll(this, 'render', 'sliderHandler','update');
this.model.on('change',this.update, this);
render: function(){
this.$el.html(_.template(html, {}));

return this;
sliderHandler: function(e){
var slider = $(e.currentTarget);
var property = slider.parents('div').attr('id');
var value = slider.slider('value');

this.model.attributes[property] = value;
update: function(){
//get changed attribute + value here



The two answers below solved it. Map the attributes to an object and give that to Backbone. Also I found another solution. Instead of an object, model.set() also accepts an array.

model.set(customattribute, value, customattribute2, value2);


I'm not sure that I fully understand your problem, but: If you want to update an attribute, just:

     customattribute: value

If you want that the setting not trigger an event, you could pass a silent option, like this:

     customattribute: value
}, {silent:true});

I hope it helps you.


Another way:

 var map = {};
 map[customattribute] = value;