我有一个带有选项的表单。我想使用backbone.stickit 将它绑定到模型,但是文档显示了如何在绑定配置上填充选择。我找不到一种简单的方法将模型与我的预填充选择绑定。
这是我的html
<div id="main">
<form id="formulario">
<input id="test1" type="text" />
<select id="test2">
<option value="0">a</option>
<option value="1">b</option>
</select>
</form>
<div id="value-test1"></div>
<div id="value-test2"></div>
</div>
这是一个基于文档的工作示例,但不是我需要的
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
el: $('#main'),
bindings: {
'#test1': 'test1',
'#value-test1': 'test1',
'#test2': {
observe:'test2',
selectOptions: {
collection: function() {
return [
{value: 0, label:'a'},
{value: 1, label:'b'}
];
}
}
},
'#value-test2': 'test2'
},
render: function() {
this.stickit();
}
});
var model = new Model({test1: 'test', test2: 0});
var view = new View({model: model}).render();
http://jsfiddle.net/camilosw/nDjHh/
我尝试使用 jquery 从绑定配置上的选择中获取选项值,但不起作用
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
el: $('#main'),
bindings: {
'#test1': 'test1',
'#value-test1': 'test1',
'#test2': {
observe:'test2',
selectOptions: {
collection: function() {
options = $("#test2 option").map(function(){
return {value: this.value, label: this.text};
}).get();
return options;
}
}
},
'#value-test2': 'test2'
},
render: function() {
this.stickit();
}
});
var model = new Model({test1: 'test', test2: 0});
var view = new View({model: model}).render();
http://jsfiddle.net/camilosw/2EYV7/2
它有效,但我认为它会在有很多选择的表格上一团糟
window.options = $("#test2 option").map(function(){
return {value: this.value, label: this.text};
}).get();
var Model = Backbone.Model.extend({});
var View = Backbone.View.extend({
el: $('#main'),
bindings: {
'#test1': 'test1',
'#value-test1': 'test1',
'#test2': {
observe:'test2',
selectOptions: {
collection: function() {
return window.options;
}
}
},
'#value-test2': 'test2'
},
render: function() {
this.stickit();
}
});
var model = new Model({test1: 'test', test2: 0});
var view = new View({model: model}).render();
http://jsfiddle.net/camilosw/Y3aEF/1
将预填充选择绑定到模型的最佳方法是什么?
我只尝试使用backbone.stickit,使用另一个库更容易吗?