javascript - 管理不受路线控制的路段的最佳方法

标签 javascript ember.js

我对如何管理页面上不使用路由的全局部分感到困惑,例如通知下拉列表。

通知下拉列表将始终可见,并应相应更新。

这是我尝试过的。

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.storenull

总的来说,实现此类功能的最佳方法是什么?

最佳答案

您可以使用命名 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/

相关文章:

javascript - jQuery 菜单不起作用,即(文档模式 : Quirks)

javascript - 在 Bootstrap 容器的开头启动光滑的 slider 并全宽滚动

Ember.js: "start"按钮在哪里?

javascript - 如何在 ember 数据中缓存查询结果

ember.js - 如何修复 Ember 1.13.9 中已弃用的 Ember.Handlebars.registerBoundHelper?

Javascript:通配符正则表达式搜索

php - 是否有适用于 PHP 或 JavaScript 的良好 JSON 格式化程序库?

Facebook 页面/选项卡中的 javascript [fbjs]

Ember.js 的 CSS 继承问题

ember.js - Ember 1.0 Final Internet Explorer 8 和 9(历史 API - pushState 和 replaceState)