javascriptsproutcoresproutcore-controllers

valueBinding to content of array


I have this controller with a value.

App.xcontroller = SC.ArrayController.create({
   ...some code...
   array_values = [],
   ..more code...
})

Now i have somewhere in a view this valueBinding

valueBinding: 'App.xController.array_values',

When I change values in the array the view does not get updated. but when i do the following in the controller:

var array_values = this.get('array_values');
...  adding / removing values to the array....  
  if (x_values.contains(x)){
    x_values.removeObject(x)
} else {
    x_values.pushObject(x);
};       
this.set('array_values', array_values.copy());

the binding works, the view gets updated. But ONLY with the copy(). I don't want to make a copy of the array, IMHO this is not efficient. I just want to let the valueBinding know content has changed..

the x values are just a bunch of integers.

The reason i want this: I want to change the value key of a SegmentedItemView. I want to change the active buttons. But I do not know on forehand how many segmentedviews I have so I thought i bind the value of every generated segemented view to some common array and change that common array to be able to change the active buttons on all of the segmented views. Since each button represents an item with an unique key it works fine. except that i have to copy the array each time.


Solution

    1. set the content property of the xcontroller
    2. Bind to the arrangedObjects property of the xcontroller
    3. You need to use KVO compliant methods on the array to get the bindings to fire. The ArrayController itself has an addObject and removeObject methods. Arrays in SC have been augmented with a pushObject method (among others), which is also KVO compliant. So if you use the KVO methods the view should update.

    The reason your view does not update is because you are bound to the array, but the array itself did not change. When you do a copy, the array itself changes, so the bindings fire.

    You might also want to try

    this.notifyPropertyChange('x_values');

    in the controller after you make the changes, but that is less preferable to using the built in KVO functionality.