rivets icon indicating copy to clipboard operation
rivets copied to clipboard

Explicitly calling `update` doesn't update bindings produced by formatters

Open lexi-lambda opened this issue 9 years ago • 2 comments

Given the following sort of code:

rivets.formatters.sum = _.sum;

var data = { vals: [1, 1, 1] };
var view = rivets.bind($('.view'), data);

data.vals[0] = 2;
view.update(data);

...with the following HTML:

<div class="view">
    { vals | sum }
</div>

The output remains at 3, while I believe it should be 4. JSFiddle here.

I understand that Rivets can't update the binding expression because it can't watch for the array changes, but shouldn't an explicit call to update fix that and force the update to propagate?

lexi-lambda avatar Jun 10 '15 17:06 lexi-lambda

I have played with this dirty workaround and got 4:

rivets.formatters.sum = _.sum;

var data = { vals: [1, 1, 1] };
var view = rivets.bind($('.view'), data);

data.vals[0] = 2;
var head = data.vals.shift();
data.vals.unshift(head);

Of course in real code I'd check the array isn't empty.

gaydenko avatar Jun 23 '15 20:06 gaydenko

If you look at how Rivets watches arrays, it watches for the Array.prototype methods such as push(), unshift() etc. So you have to treat arrays with care if you want to watch them using Rivets. For example, when I want to rebuild an array that's being watched by Rivets from scratch, I can't just do arr = newArr. I have to do something like the following (using es6 syntax):

arr.length = 0;
arr.push(...newArr);

Done like this, Rivets handles it beautifully. I am using Rivets on a huge, complex application and I never once need to call update(), I don't think you should need to either.

benadamstyles avatar Jun 24 '15 11:06 benadamstyles