0

If I have a list on a page, and it is using knockout's foreach binding to display list items, then something else updates the DOM to add an extra list item. If there any way I can get knockout to detect that DOM change and update its model to add the new item to the observableArray?

Here is a fiddle which shows the problem...

http://jsfiddle.net/BGdWN/1/

function MyViewModel() {
    this.items = ko.observableArray([
        { name: 'Alpha' }, { name: 'Beta' }, { name: 'Gamma' }, { name: 'Delta' }
    ]);

    this.simpleShuffle = function() {
        this.items.sort(function() {
            return Math.random() - 0.5; // Random order
        });
    };

    this.simpleAdd = function() {
         $("#top").append("<li>New item</li>");
    }
}

ko.applyBindings(new MyViewModel());

It has 2 lists bound to the same observableArray, click the addItem button and you can see that the DOM is updated to include the new list item in the top list, but I would like the second list to be updated too, all via the model.

It seems that knockout ignores DOM elements that it didnt render, you can see this by clicking the shuffle button, it leaves the new items there. I would have expected it to remove them and do a full re-render.

Please don't answer with "Just add the item to the observableArray"

Dean North
  • 3,741
  • 2
  • 29
  • 30
  • **KO does not support this** so "Just add the item to the observableArray". Otherwise you can probably write a custom binding handler which listens to the DOM changes and populates the observable array.... but I would suggest that you "Just add the item to the observableArray" – nemesv May 01 '13 at 16:22
  • I thought this would be the case, I may have to write a custom binding then :-( – Dean North May 01 '13 at 16:32

1 Answers1

1

Take a look at the first link and the second link Interface MutationEvent

See Fiddle

$('#top').bind('DOMNodeInserted DOMNodeRemoved', function () {
    alert('Changed');
});

I hope it helps.

Community
  • 1
  • 1
Damien
  • 8,889
  • 3
  • 32
  • 40