我在 ember.js 中遇到以下问题。子 Controller 取决于父 Controller 中的选定值以确定其内容。在数据库中,一个 child 有一个 parent_id 引用。
App.parentsController = Em.ArrayController.create({
content: [],
selected: null
});
App.sonsController = Em.ArrayController.create({
// the value of content depends on the id of
// the selected item in the parentsController
content: [],
selected: null
});
App.daughtersController = Em.ArrayController.create({
// the value of content depends on the id of
// the selected item in the parentsController
content: [],
selected: null
});
我宁愿在 parentsController 不必了解其他 Controller 的情况下解决这个问题。这应该可以通过观察者、绑定(bind)甚至通过计算来实现,但我不知道从哪里开始。任何帮助将不胜感激。
最佳答案
您可以使用绑定(bind)系统。 sonsController
需要观察 parentsController.selected
属性,然后更新它的内容。
这是一个如何做到这一点的例子:
App.parentsController = Em.ArrayController.create({
content: [],
selected: null
});
App.sonsController = Em.ArrayController.create({
parentControllerBinding: 'App.parentsController',
content: [],
updateContent: function() {
var selected = this.getPath('parentController.selected');
var newContent = Ember.A();
newContent.pushObject(selected);
this.set('content', newContent);
}.observes('parentController.selected')
});
和here is the jsfiddle associated .
注意:您也可以直接绑定(bind)所选属性:
App.sonsController = Em.ArrayController.create({
parentSelectedBinding: 'App.parentsController.selected',
...
updateContent: function() {
...
}.observes('parentSelected')
})
关于javascript - 如何从 Ember.js 中另一个 ArrayController 的选定值更新一个 ArrayController 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10917706/