我有一个 ProfilesController
和一个代表单个配置文件的 ProfileController
。
// Profiles listing
App.ProfilesController = Ember.ArrayController.extend({
});
// Single Profile representation
App.ProfileController = Ember.ObjectController.extend({
isActive: false,
actions: {
edit: function() {
// TODO: disable all profiles
// does not work ... parentController is undefined. pseudo code only!
this.get('parentController.children').forEach(function(profile) {
profile.set('isActive', false);
});
// enable current profile
this.set('isActive', true);
}
}
});
请注意,这不是完整的代码,这两个 Controller 在我的应用程序中具有更多代码,并且还有一个 ProfileView 可以使配置文件列表成为可能。
重要的部分是如何从 ProfileController 中访问父 ProfilesController(ArrayController)?
我已经尝试过(在编辑操作中):
this.get('parent') // => undefined
this.get('parentController') // => null
this.get('target') // => null
编辑:同时,我沿着对象树向下查找,想出了一个令人难以置信的 hacky 但有效的解决方案:
// disable all profiles
this.get('controllers.profiles.target._activeViews.profiles.0._childViews.0._childViews').forEach(function(childView) {
childView.get('_childViews.0.controller').set('isActive', false);
});
我想,直到我更改模板结构中的某些内容为止,它都会起作用。必须有一种更干净的方法来做到这一点:-D
编辑 2:为了澄清一点,这里是我的配置文件模板,其中 profiles
是配置文件模型的集合(不是 Controller !每个模型都由一个 Controller ,因为我必须存储应用程序状态,例如当前事件配置文件等):
{{#each profile in profiles}}
{{view App.ProfileView profileBinding=profile}}
{{/each}}
和配置文件 View
App.ProfileView = Ember.View.extend({
templateName: 'profiles/profile',
init: function() {
this._super();
var profile = this.get('profile');
// Here I explicitely create a ProfileController instance,
// otherwise ProfilesController would be used instead of ProfileController
// because in EmberJS by default the View's controller is always the parent controller
this.set('controller', App.ProfileController.create());
var controller = this.get('controller');
controller.set('profile', profile);
}
});
最佳答案
您可以在 each
循环中设置 itemController
属性,这样您就不必手动创建 ProfileController
。
{{#each profile in profiles itemController="profile"}}
{{view App.ProfileView profileBinding=profile}}
{{/each}}
然后您可以使用 needs
来确保将对 ProfilesController
的引用注入(inject)到每个 ProfileController
中。您可以使用 this.get('controllers.profiles')
访问 ArrayController
本身。如果您采用 Ember Way 进行操作,则需要访问该 Controller 的 content
属性 (this.get('controllers.profiles.content')
) 。看来您没有按照 Ember Way 进行操作,而是将集合保存到该 Controller 的 profiles
属性,而不是 content
属性。在这种情况下,您可以使用 this.get('controllers.profiles.profiles')
。 profiles
的第一个实例获取 ProfilesController
,第二个实例获取在该 Controller 上设置的 profiles
属性。
App.ProfileController = Ember.ObjectController.extend({
needs: ['profiles'],
actions: {
edit: function() {
this.get('controllers.profiles.profiles').forEach(function(profile) {
profile.set('isActive', false);
});
// enable current profile
this.set('isActive', true);
}
}
});
关于javascript - EmberJS - 如何从子 Controller 内访问父 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19253143/