【问题标题】:How to observe a computed property in EmberJS? Creating a FB like notification feature如何观察 EmberJS 中的计算属性?创建类似 FB 的通知功能
【发布时间】:2015-11-17 06:09:02
【问题描述】:

我正在为我的应用程序构建通知功能,就像 Facebook 的通知一样。我几乎让它工作了,但无法观察计算属性。

这是场景:

有很多交易,当交易更新时(比如它的名称/价格发生变化),通知是通过 RabbitMQ 发送的。我们发送的对象负载,它有一个属性“状态”,可以是“已读”或“未读”。

控制器:

notificationsCount: function() {
  var notifications = this.get('notifications');
  var unreadCount = 0;
  for (var i = 0; i < notifications.length; i++) {
    if (notifications[i].status == 'unread') {
      unreadCount++;
    }
  }
  return unreadCount;
}.property('notifications.[]'),

这里,最初的“通知”是一个空数组。所有来自 RMQ 作为对象有效负载的通知都在其中。这个“未读计数”是我想在通知图标上显示的有点像小徽章。

当我点击通知图标时,所有通知的状态都应该从“未读”变为“已读”。

控制器:

action:{
    readNotifications: function () {
      var notifications = this.get('notifications');
      for (var i = 0; i < notifications.length; i++) {
        notifications[i].status = 'read';
      }
   },
}

通过调试,我发现到目前为止一切正常。但我想要的是,一旦用户点击通知图标并且所有通知都标记为已读,notificationCount 应该设置为零,因为不再有任何未读通知。

理论上,我必须在 readNotifications 操作中观察通知计数或执行通知计数一次。但我找不到办法做到这一点。如果有其他方法,欢迎分享。

提前致谢。

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    简而言之,您应该定义您的 notificationsCount 计算属性来监听 notifications.@each.status 而不是 notifications.[].[] 在数组内容更改(添加或删除元素)时触发,而.@each.prop 在任何数组元素的prop 属性更改时触发。

    详情请参阅the relevant Ember.js docs

    此外,您可以使用NativeArray 方法使您的代码更简洁(因为您已经在使用.property() 简写,因此您确实启用了原型扩展)。你的整个notificationsCount 可以写成

    notificationsCount: function() {
        return this.get('notifications').filterBy('status', 'unread').length;
    }.property('notifications.@each.status'),
    

    你的行为

    readNotifications: function () {
       this.get('notifications').setEach('status', 'read');
    },
    

    【讨论】:

    • 太棒了!像魅力一样工作。也感谢你重构代码:)
    • @anmol 然而,一般来说,原型扩展存在一些“争议”,​​你可能想也可能不想承诺。您还可以使用Ember.computed(...) 语法定义计算属性。 Ember.computed
    猜你喜欢
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2017-04-25
    • 2016-04-22
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多