2

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?

Community
  • 1
  • 1
crush
  • 16,713
  • 9
  • 59
  • 100

1 Answers1

6

After searching Google for how to apply bindings to a specific element, I came across this StackOverflow question detailing how to apply KnockoutJS to a partial view.

The second parameter of ko.applyBindings can be a specific element of the DOM to serve as the root of the view. Therefore, in my binding handler, I can simply do the following:

ko.applyBindings(viewModel, $childElement[0]);

Notice: You can't pass a jQuery object to it. It must be a DOM element.

Community
  • 1
  • 1
crush
  • 16,713
  • 9
  • 59
  • 100