I created a custom binding that moves a DOM node to before the current DOM node. The moved DOM node has a text binding on it. To be clear, this looks something like the following simplified example [jsfiddle]:
HTML
<div data-bind="myBinding: myObservable">
<div data-bind="text: myOtherObservable"></div>
</div>
KnockoutJS Binding
ko.bindingHandlers.myBinding = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var $element = $(element),
$childElement = $element.find('div');
//Move the inner div to before the current div, and it won't get evaluated.
$(element).before($childElement);
}
};
KnockoutJS ViewModel
function ViewModel() {
this.myObservable = ko.observable(false);
this.myOtherObservable = ko.observable("Test");
}
ko.applyBindings(new ViewModel());
The Problem
The text binding doesn't get applied on the inner child node. I assume this is because the DOM tree is walked from top to bottom. When the child node gets moved before the current node, it is now prior to the current node, and will be skipped when the DOM is traversed forward.
My actual binding needs to move the div before the current div. However, I need the bindings to be applied.
Question
Is it possible to manually apply the binding on the child DOM node before I move it within my binding handler? If so, how can it be done?