使用 backbone 模型填充 select 字段的选项
using a backbone model to fill options of a select field
我想用 "static" 模型的属性填充 select 字段的选项。例如,我有一个模型和美国各州的集合:
State = Backbone.Model.extend({
label:'',
value:''
}) ;
STATES = Backbone.Collection.extend({
model: State
});
states = [
{label: "Select ", value: '__' },
{label: "Alabama ", value: 'AL' },
{label: "Alaska ", value: 'AK' },
{label: "Arizona ", value: 'AZ' },
....];
localstates = new app.STATES(states); // or fetch the list of states from a RESTful site.
然后我使用返回表单有任何地址视图,我想将 localstates 传递到表单中以填充状态字段的选项:
UserAddress = Backform.Form.extend({
el: $("#personalInformation"),
fields: [
{name: "address1", label: "Address1", control: "input"},
{name: "address2", label: "Address2", control: "input"},
{name: "city", label: "City", control: "input"},
{name: "state", label: "State", control: "select",
options: **localstates**,
{name: "zip", label: "Zip Code", control: "input"},
{control: "button", label: "Save to server"}
],
});
我猜我需要以某种方式将状态集合传递到用户地址视图,然后访问属性。但是我还没有找到一个很好的例子来说明如何做到这一点。
edit1:好的,在这种情况下这有点傻但是:
newstate = new app.STATES(app.states);
var allstates =[];
app.newstate.forEach(function(state){
allstates.push({"label": state.get("label"), "value" : state.get("value")});
})
给我和我可以在 localstate 使用的数组。在这种情况下,基本上我只是重新创建了我的原始数组。在从服务器获取数据的情况下,它会很有用,但有没有更好的方法?
您可以 localstates.toJSON()
获取要在模板中使用的值的副本。
我想用 "static" 模型的属性填充 select 字段的选项。例如,我有一个模型和美国各州的集合:
State = Backbone.Model.extend({
label:'',
value:''
}) ;
STATES = Backbone.Collection.extend({
model: State
});
states = [
{label: "Select ", value: '__' },
{label: "Alabama ", value: 'AL' },
{label: "Alaska ", value: 'AK' },
{label: "Arizona ", value: 'AZ' },
....];
localstates = new app.STATES(states); // or fetch the list of states from a RESTful site.
然后我使用返回表单有任何地址视图,我想将 localstates 传递到表单中以填充状态字段的选项:
UserAddress = Backform.Form.extend({
el: $("#personalInformation"),
fields: [
{name: "address1", label: "Address1", control: "input"},
{name: "address2", label: "Address2", control: "input"},
{name: "city", label: "City", control: "input"},
{name: "state", label: "State", control: "select",
options: **localstates**,
{name: "zip", label: "Zip Code", control: "input"},
{control: "button", label: "Save to server"}
],
});
我猜我需要以某种方式将状态集合传递到用户地址视图,然后访问属性。但是我还没有找到一个很好的例子来说明如何做到这一点。
edit1:好的,在这种情况下这有点傻但是:
newstate = new app.STATES(app.states);
var allstates =[];
app.newstate.forEach(function(state){
allstates.push({"label": state.get("label"), "value" : state.get("value")});
})
给我和我可以在 localstate 使用的数组。在这种情况下,基本上我只是重新创建了我的原始数组。在从服务器获取数据的情况下,它会很有用,但有没有更好的方法?
您可以 localstates.toJSON()
获取要在模板中使用的值的副本。