batilc
batilc

Reputation: 741

KnockoutJS - UI not updating with built-in observableArray methods except push and pop

When I do a push or pop operation on my observable array, it is reflected in the ui. However other operations on the array won't change anything in the UI. Here's an example of my case:

<ul data-bind="foreach: addresses">
     <!-- ko template: {name: 'AddressItemTemplate', data: {address: $data, page: 'update-page'} }-->
     <!-- /ko -->
</ul>

I use my template in two different pages and thats the reason I am using the template data like that.

<script type="text/html" id="AddressItemTemplate">
    <p data-bind="text: (page == 'update-page') ? 'updating' : 'declined'"</p>
    <p data-bind="text: address.title"></p>
</script>

Now on js side, ofc I declared the addresses as an observable array

this.addresses = ko.observableArray([addresObject1, addressObject2, ...])

Somewhere on the page, I edit the address values. To have UI reflecting the changes, I do the following:

//suppose we know that the first address is being edited
var tmp_addresses = addresses();
tmp_addresses[0].title = 'blabla';
addresses(tmp_addresses);

And there it is, in the viewModel, I can see that the content of the addresses has been updated, but not in the UI??

addresses.push(someAddressObject);

or

addresses.pop();

works (updates the UI with the new/removed element). But addresses.splice(0, 1, newAddressObject) does not do anything in the UI again.

What am I missing here? How can push pop work and not the others?? Am I experiencing a bug in knockout framework?

UPDATE

I found out a way to do it, but there's something wrong. I'll come to that but first:

I am well aware that if I use observable objects in the observable array, the changes would be reflected in UI. However that is exactly the thing I want to avoid. It is an overkill.

Observable properties should be required in cases where properties are really exposed to user interaction. For example, if you have a UI for setting each of the fields of an object, then yes, observable property would be the right call.

However in my case, I dont even have a UI for updating the address field. Moreover, I dont need tinkering and constantly watching all the properties of all the addresses. In my case, every now and then an update occurs from the server and that changes only a single field in a single address field.

On another perspective the way I suggest should work. I simply update the whole array at once, not every element individually. It's the exactly the same logic with:

someObservableObject({newObject: withNewFields, ...});

Thats why I dont need my objects as observables. I simply want to re-declare the array and be done with the change. For example, it is advised that if you are going to make lots of pushes into the observable array, dont use array.push(...) multiple times, instead re-declare the larger array on to the observable array variable in a similar way I do it in my question. Otherwise, I am telling knockout to track every single object and every single field in them, which is hardly what I want.

Now, I finally got it working but the way I do suggests that there is a cleaner way to do it.

I found out that, the items in the observable array are somehow tracked and not updated when you re-declare the array with them. For example the code I gave in the question would not work. However the code below works:

var tmp_addresses = addresses();
var tmp_addr = tmp_addresses[0];
var new_addr = {};
Object.keys(tmp_addr).forEach(function(key){
    new_addr[key] = tmp_addr[key];
});
new_addr.title = 'Hey this is something new!'
addresses.splice(0, 1, new_addr);

Not satisfied? The code below is going to work as well, because we are re-defining the array:

var newAddressObject1 = {...}, newAddressObject2 = {...};
addresses([newAddressObject1, newAddressObject2]);

But the following would not work!

var tmp_addresses = addresses();
var tmp_addr = tmp_addresses[0];
tmp_addr.title = 'Hey this address wont update';
addresses.splice(0, 1, tmp_addr);

How come? I think knockout adds an internal property to his items in observableArrays and when I try to reinsert one, it will not update.

My problem has now morphed into creating a new object with the same properties of the desired item in the observable array. The way I coded above is simply very dirty-looking. There's gotta be a better way to do that

Upvotes: 0

Views: 2454

Answers (2)

batilc
batilc

Reputation: 741

The problem was exactly as @jason9187 pointed out in the comments: The references of the objects in the observable array does not change when I edit a field of them. Therefore, KO would not interpret my array as changed. If the observableArray had contained simple data types, then the way I suggested could work without a problem. However, I have an Object in the array, therefore although I edit the Object, it's reference (pointer) remains the same, and KO thinks that all Objects are the same as before.

In order to achieve what I wanted, we have to solve the deep cloning problem in javascript like in this post.

Now there's a trade-off there, deep cloning is very simple in vanilla if you don't have a circular architecture or functions in your objects. In my case, there's nothing like that. The data comes from a restful API. If anybody in the future gets hold of this problem, they need to deep-clone their 'hard-to-clone' objects.

Here's my solution:

var tmp_addresses = JSON.parse(JSON.stringify(addresses())); //Creates a new array with new references and data
tmp_addresses[0].title = 'my new title';
addresses(tmp_addresses);

Or, if you can create address objects, following will work as well:

var tmp_addresses = addresses();
tmp_addresses[0] = new randomAddressObject(); 
addresses(tmp_addresses);

Here is a fiddle that I demonstrate both of the methods in a single example

Upvotes: 0

super cool
super cool

Reputation: 6045

You are wrongly assigning value to observable title that is the reason why UI not reflecting its changes (2 way binding broken).

Thumb rule is always use () notation while assigning a value to observable (keeps two way binding intact)

viewModel:

var ViewModel = function () {
    var self = this;
    self.addresses = ko.observableArray([{
        'title': ko.observable('one')
    }, {
        'title': ko.observable('two')
    }])
    setTimeout(function () {
    var tmp_addresses = self.addresses();
    tmp_addresses[0].title('blabla'); //assigning data to observable 
    self.addresses(tmp_addresses);
    }, 2000)
};
ko.applyBindings(new ViewModel());

working sample here

PS: Don't get deceived by seeing the value change in viewModel the moment you done assigning using = two binding is broken UI wont reflect VM'S changes .

when you splice up your observableArray UI takes it changes check here

Upvotes: 2

Related Questions