1

It seems knockout destroys bindings on detached elements. So if I apply a binding and detach that element, not only will that binding not be computed while the element is detached but it will still be broken after the element is re-inserted back into the document.

So something like:

ko.applyBindings(items, $list[0]);

items.push('one');

$list.detach();

items.push('two');

$container.append($list);

items.push('three');

Here's a fiddle: http://jsfiddle.net/nicholasstephan/KejYc/2/

The binding in $list should read one, two three, but instead every update after the detach is not computed.

What should I be doing here to make this work?

nicholas
  • 14,184
  • 22
  • 82
  • 138

1 Answers1

1

Applying the bindings at the end makes your fiddle work. But I don't imagine that's what you are shooting for:

var $container = $("#container");
var $list = $('#list');
var items = ko.observableArray([]);

items.push('one');
$list.detach();
items.push('two');
$container.append($list);
items.push('three');
ko.applyBindings(items, $list[0]);

This SO thread suggests you just re-apply bindings after each detach or simply hide the elements instead of detaching them. There are also several comments suggesting that the approach be rethought in this case, which seems to be the best answer.

Perhaps you could provide the desired behavior rather than a contrived example? That would probably go a long ways to suggesting alternative models. Assuming your goal is to create draggable elements (Off the cuff, it's the only really likely scenario where I'd need to detach/re-insert elements), you could take an approach like this:

  1. drag initiated
  2. drag a copy of the element (leave original in doc)
  3. drag stopped
  4. copy any necessary data from original to copy
  5. insert the copied element at the new/valid location
  6. delete the old element
  7. call ko.applyBindings on the new element
Community
  • 1
  • 1
Kato
  • 40,352
  • 6
  • 119
  • 149
  • Thanks. I'm running into this problem in a tabbed application. I tried to detach inactive tabs to keep the DOM clean. It's a pretty hefty app, so I thought every bit would help. Simply hiding them has solved the problem. But that begs the question: do hidden DOM elements have any effect on browser performance? Cheers. – nicholas Nov 26 '12 at 20:53
  • It should perform great if you are using `display: none`; the element is actually removed from the DOM in this case. `Visibility: hidden`, on the other hand, will affect performance. You might consider posting a screenshot or description of your UI on `user experience` and seeing what suggestions they have; has to be a better model than tabs! – Kato Nov 27 '12 at 00:29