【问题标题】:EmberData manage model in controller without routeEmberData 在没有路由的控制器中管理模型
【发布时间】:2014-04-28 20:47:57
【问题描述】:

我的应用程序的一部分从主模板分离到一个单独的把手模板中,使用{{render "header"}} 将其呈现在正确的位置。 这个单独的模板也有它自己的控制器来显示来自模型的一些数据 (App.Notification)。 我想要做的是显示有限数量的notifications 和新通知的总数。 当控制器的 notifications 属性在每个循环中被调用时,Ember 数据从服务器加载 10 个条目,但是一旦我尝试通过 splice 限制显示的通知数量,它就不会返回任何数据。

基本上,如果我无法在路由中设置控制器模型,我将无法处理模型数据,我认为这就是为什么 slice 的正常语法在这种情况下不起作用的原因。 我已经搜索了 Stackoverflow 和 Ember 文档,但只找到了正常 Route -> Controller 设置的示例,但没有关于这个特定主题,所以问题是,如何在这个设置中正确处理模型数据?

标题控制器:

App.HeaderController = Ember.Controller.extend
  notificationNew: (->
    @get('notifications').filterBy('seen', false).get('length')
  ).property('notifications')

  notifications: (->
    @store.find('notification').slice(0, 2)
  ).property('@each.notification')

模板:

{{#each notifications}}
 ...
{{/each}}

【问题讨论】:

    标签: ember.js controller ember-data models


    【解决方案1】:

    要通过命名约定在不直接与路由关联的控制器上设置属性,请参考以下jsbin。

    http://emberjs.jsbin.com/gugajaki/3/edit

    App = Ember.Application.create();
    
    notifications = [
      {seen: false, message: "tornado siren!!"}
      {seen: true, message: "Omg lol security breach"}
      {seen: false, message: "BFF Rite?"}
      {seen: false, message: "steve kane 4 prez?"}
    ]
    
    App.HeaderController = Ember.Controller.extend
      newNotifications: Ember.computed.filterBy("notifications", "seen", false)
    
    
    App.ApplicationRoute = Ember.Route.extend
      setupController: (controller, model) ->
      headerController = this.controllerFor("header")
    
      #this can be a remote fetch via find.  will work the same
      headerController.set("notifications", notifications)
    

    链接中将解决您发布的代码中的几个问题,但为了清楚起见,我将在此处列举:

    1. 您可以直接在模板中使用长度属性
    2. 使用 Ember.computed.filterBy 获得非常有效的数组观察结果
    3. 使用应用程序路由的“controllerFor”方法配置头控制器的单例实例
    4. 我不懂拼接,但无论如何我都不会这样做

    希望这会有所帮助。

    【讨论】:

    • 感谢您的快速回复,这对我很有帮助!虽然有些东西我不明白。您说无论如何您都不会使用拼接,但是只有部分条目的正确方法是什么? Ember 数据加载 10 个通知,并且使用 splice 仅获取前 5 个通知是我迄今为止看到的唯一方法。另外,我仍然需要计算控制器中的newNotifications 以检查是否有。使用hasNew: function(){ return this.get("newNotifications").get("length"); }.property('newNotifications') 之类的内容是否正确?
    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2016-04-05
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多