anmol.agrawal
anmol.agrawal

Reputation: 39

How to observe a computed property in EmberJS? Creating a FB like notification feature

I am building notification feature for my app just like Facebook's notification. I have almost made it work but just unable to observe a computed property.

Here is the scenario:

There are many deals and when a deal is updated(like it's name/ price is changed), the notification is sent through RabbitMQ. The object payload that we send, it has an attribute "status" which could be 'read' or 'unread'.

controller:

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.[]'),

Here, initially 'notifications' is an empty array. All the notifications coming from RMQ as object payloads goes inside this. This 'unreadCount' is what I want to show kinda like a small badge over the notification icon.

When I click the notification icon, all the notifications' status should change to 'read' from 'unread'.

controller:

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

Through debugging, I found everything is working fine till this point. But what I want is, once the user clicks the notification icon and all the notifications are marked as read, the notificationCount should be set as zero as there are no more any notifications that is unread.

Theoretically, I have to either observe notificationsCount or execute notificationsCount once inside readNotifications action. But I couldn't find a way to do it. If there is any other way, feel free to share.

Thanks in advance.

Upvotes: 0

Views: 119

Answers (1)

Thernys
Thernys

Reputation: 723

The short of it is that you should define your notificationsCount computed property to listen to [email protected] instead of notifications.[]. .[] triggers when the array contents change (elements are added or removed), while an [email protected] triggers when the prop property on any array element changes.

Refer to the relevant Ember.js docs for details on this.

Additionally, you can make your code more concise using NativeArray methods (because, since you are already using the .property() shorthand, you do have prototype extension enabled). Your entire notificationsCount could be written as

notificationsCount: function() {
    return this.get('notifications').filterBy('status', 'unread').length;
}.property('[email protected]'),

and your action as

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

Upvotes: 1

Related Questions