我对如何管理页面上不使用路由的全局部分感到困惑,例如通知下拉列表。
通知下拉列表将始终可见,并应相应更新。
这是我尝试过的。
在ApplcationContoller
上设置通知
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('notifications', this.store.find('notification'));
}
});
并在 ApplicationTemplate
<script type="text/x-handlebars">
{{#each notifications}}
Message: {{message}}
{{/each}}
<script>
虽然这有效,但似乎不太正确,因为我希望通知至少有自己的 Controller 。
所以我不知道如何为通知分配 Controller ,因此我为通知创建了一个 View ,并尝试以这种方式分配 Controller ,如下所示。
创建了通知 View
App.NotificationsView = Ember.View.extend({
controller: App.NotificationsController.create(),
templateName: 'notifications'
});
创建通知模板
<script type="text/x-handlebars" data-template-name="notifications">
Notifications
</script>
创建了NotificationsController
App.NotificationsController = Ember.Controller.extend({
init: function() {
this._super();
this.set('content', this.store.find('notification'));
}
});
我收到以下错误。
Uncaught TypeError: Cannot call method 'find' of null
这显然是在说 this.store
是 null
总的来说,实现此类功能的最佳方法是什么?
最佳答案
您可以使用命名 socket 并实现所需的行为:
将命名导出添加到您想要呈现通知的模板:
<script type="text/x-handlebars">
{{outlet notificationsOutlet}}
{{outlet}}
<script>
在相应的路由中设置 Controller :
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
this.controllerFor('notifications').set('model', this.store.find('notification'));
}
...
});
并渲染到指定的 socket 中:
App.ApplicationRoute = Ember.Route.extend({
...
renderTemplate: function(controller, model) {
this._super(controller, model);
this.render("notifications", {
into: "application", // should be possible to leave this one out
outlet: "notificationsOutlet",
controller: this.controllerFor("notifications")
});
}
});
更新:
或更短:使用{{render}}
帮助器!
再次像上面一样设置 Controller :
App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
this.controllerFor('notifications').set('model', this.store.find('notification'));
}
...
});
更简单的渲染渲染:渲染助手允许您渲染按名称指定的 Controller 和 View 。
<script type="text/x-handlebars">
{{render notifications}}
{{outlet}}
<script>
您可以找到这两种技术的更一般描述 here .
关于javascript - 管理不受路线控制的路段的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840296/