Two or more instances of an controller shares the same property (an array)


#1

Hello guys,

I have a controller that has an array with items that is rendered in the template. This array is defined as empty (Ember.A([]) ). This controller has an action “addItem” that has an item parameter and adds the item into the array item that is saved on the controller. Bellow you can find the lines from the controller:

var NotificationsController = Ember.Controller.extend({
    notifications: Ember.A([]),

    actions: {
        addNotification: function(msg){
                var notifications = this.get('notifications');
                notifications.pushObject(msg);
        }
    },
 ....
}

The addNotification action comes from another action based on the user actions. Basically this message notification should notice the user that an operation is running and he need to wait for the feedback.

The notification entity (controller + template) are rendered in a each statement. When two or more notifications are rendered, the notifications array is shared between all instances of this controller and all instance should have his individual array with notifications.

From my point of view, each instance of controller should have his own notification array object. This means that if a controller receives the “addNotification” action, only the notification array from that instance should be changed and the notification arrays from the other controllers should remain empty as it was defined.

What should I change to the controller to have an different notifications array for each instance of the controller? Please advice.

Kind Regards,


#2

Since a Controller is a Singleton Object, your best bet is to not include a Controller, but to write a Mixin which then could be used in every Controller which should be able to show notifications. :smiley:


#3

I removed the above controller and I have created the following mixin:

var NotificationsMixin = Ember.Mixin.create({
    notifications: Ember.A([]),

  actions: {
      addNotification: function(msg){
          var notifications = this.get('notifications');
          notifications.pushObject(msg);
      }
  }
});

I added this mixin on an existing controller that is rendered in the same each statement, but I have the same result: the notifications property array is shared between all instances of this new controller.

Am I missing anything or do you have another suggestion ? Please advice.

Kind Regards,


#4

Because You define the property as a prototype property, Try to define it as the instance property, in Init method