Jar*_*ish 15 javascript arrays object backbone.js
故事:我有很多需要设置的属性.由于它们有相似之处,我选择读出类,输入框是属性名称的一部分.
问题:可以设置对象的动态属性,就像关联数组一样.所以我能做到
var customattribute = this.$el.parents('div').attr('id');
var value = $(e.currentTarget()).val();
this.model.attributes[customattribute] = value;
Run Code Online (Sandbox Code Playgroud)
但这不会触发模型的更改事件.我可以手动触发更改事件,但这不会更新this.model.changedAttributes(),我只需要设置更改的属性,而不是每个属性.
这当然也不起作用:
this.model.set(customattribute: value);
Run Code Online (Sandbox Code Playgroud)
那我该如何处理这个问题呢?
我有可以设置的ALOT(200+)属性,我不想为每个属性创建单独的eventlisteners,除非这是唯一的方法.
码:
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, {}));
this.$('.slider').slider();
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(){
console.log(this.model.changedAttributes());
//get changed attribute + value here
},
});
Run Code Online (Sandbox Code Playgroud)
编辑:
下面的两个答案解决了它.将属性映射到对象并将其提供给Backbone.我也发现了另一个解决方案 model.set()也接受一个数组,而不是一个对象.
model.set(customattribute, value, customattribute2, value2);
Run Code Online (Sandbox Code Playgroud)
Ait*_*ito 27
我不确定我是否完全理解您的问题,但是:如果您想要更新属性,只需:
this.model.set({
customattribute: value
});
Run Code Online (Sandbox Code Playgroud)
如果您希望该设置不触发事件,您可以传递一个静默选项,如下所示:
this.model.set({
customattribute: value
}, {silent:true});
Run Code Online (Sandbox Code Playgroud)
我希望它对你有所帮助.
更新:
其他方式:
var map = {};
map[customattribute] = value;
this.model.set(map);
Run Code Online (Sandbox Code Playgroud)
你需要这样做
var attributeName = this.$el.parents('div').attr('id');
var value = $(e.currentTarget()).val();
var attribute = {};
attribute[attributeName] = value;
this.model.set(attribute);
Run Code Online (Sandbox Code Playgroud)
如果属性是"test"而值'value'则与它相同
this.model.set({test: 'value'});
Run Code Online (Sandbox Code Playgroud)
这是正确设置属性并通过模型更改事件传播到您的视图的内容