我是 ember 的新手,所以也许我做错了。
我正在尝试创建一个选择下拉列表,其中填充了从外部数据源提供的三个值。我还希望根据存储在不同模型中的值在列表中选择正确的值。
我见过的大多数示例都涉及静态定义的下拉菜单。到目前为止,我所拥有的是:
{{#view contentBinding="App.formValues.propertyType" valueBinding="App.property.content.propertyType" tagName="select"}}
{{#each content}}
<option {{bindAttr value="value"}}>{{label}}</option>
{{/each}}
{{/view}}
在我的模块中:
App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
content: [
Ember.Object.create({"label":"App","value":"app", "selected": true}),
Ember.Object.create({"label":"Website","value":"website", "selected": false}),
Ember.Object.create({"label":"Mobile","value":"mobile", "selected": false})
]
});
最后是我的对象:
App.Property = Ember.Object.extend({
propertyType: "app"
});
App.property = Ember.Object.create({
content: App.Property.create(),
load: function(id) {
...here be AJAX
}
});
下拉列表将填充,但它的选定状态不会反射(reflect) App.property 的值。我知道我遗漏了一些部分,我需要有人告诉我应该往哪个方向走。
最佳答案
答案是在 formValues 上使用 .observes()。出于某种原因 .property() 会抛出一个错误,但 .observes() 不会。
我已经在此处发布了完整的 AJAX 解决方案以供引用,并将根据任何进一步的发展对其进行更新。
App.formValues = {};
App.formValues.propertyType = Ember.ArrayProxy.create({
content: [],
load: function() {
var that = this;
$.ajax({
url: "/api/form/propertytype",
dataType: "json",
success: function(data) {
that.set("content", []);
_.each(data, function(item) {
var optionValue = Ember.Object.create(item);
optionValue.set("selected", false);
that.pushObject(optionValue);
});
that.update();
}
});
},
update: function() {
var content = this.get("content");
content.forEach(function(item) {
item.set("selected", (item.get("value") == App.property.content.propertyType));
});
}.observes("App.property.content.propertyType")
});
App.formValues.propertyType.load();
关于javascript - ember.js <select> 由两个不同的对象填充和选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9021219/