我正在为我的应用程序构建通知功能,就像Facebook的通知一样。我几乎做到了,但就是无法观察到一个计算的属性。
这是一个场景:
有很多交易,当交易更新时(比如名称/价格更改),通知会通过RabbitMQ发送。我们发送的对象负载,它有一个属性"status",可以是"read"或"unread"。
控制器:
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.[]'),
这里,最初的"notifications"是一个空数组。所有来自RMQ的通知都作为对象有效载荷进入其中。这个"未读取计数"是我想在通知图标上显示的,有点像一个小徽章。
当我单击通知图标时,所有通知的状态都将从"未读"更改为"已读"。
控制器:
action:{
readNotifications: function () {
var notifications = this.get('notifications');
for (var i = 0; i < notifications.length; i++) {
notifications[i].status = 'read';
}
},
}
通过调试,我发现到目前为止一切都很好。但我想要的是,一旦用户单击通知图标,并且所有通知都标记为已读,则notificationCount应设置为零,因为不再有任何未读通知。
理论上,我必须在readNotifications操作中观察notificationsCount或执行notificationsCoount一次。但我找不到办法。如果有其他办法,请随意分享。
提前谢谢。
简而言之,您应该定义notificationsCount
计算属性来侦听notifications.@each.status
而不是notifications.[]
。当数组内容发生变化(添加或删除元素)时,.[]
会触发,而当任何数组元素的prop
属性发生变化时,.@each.prop
会触发。
有关这方面的详细信息,请参阅相关的Ember.js文档。
此外,您可以使用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');
},