1
votes

I have an outer div that is bound to a view model with ProcessClick function and an inner div that is at runtime is bound to a different view model, but with the same function name for click. For some reason only an outer model's function also gets called before an inner VM's function does.

Markup:

<div id="max-outer">
   <span data-bind="click: BindInner">Bind Inner</span>
    <br/>
    <br/>
   <span data-bind="click: ProcessClick">Outer</span>
   <div id="max-inner">
      <span data-bind="click: ProcessClick">Inner</span>
       <br/>
   </div>
</div>

JS:

function InnderModel() {
    self = this;

    self.ProcessClick = function () 
        {
            alert("Inner clicked");
        };
}

function OuterModel() {
    self = this;

    self.ProcessClick = function (){
            alert("Outer clicked");
        };

    self.BindInner = function () {
        ko.cleanNode(document.getElementById("max-inner"));
        ko.applyBindings(new InnderModel(), document.getElementById("max-inner"));
    };
}

ko.applyBindings(new OuterModel(), document.getElementById("max-outer"));

Here is a fiddle: http://jsfiddle.net/mpavlov/H2ZnV/8/

An idea is that clicking Bind inner and the clicking on Inner span would only show "Inner Clicked" alert, not both. Can this be achieved somehow?

1

1 Answers

5
votes

The inner span will get bound the first time that applyBindings is called.

Calling ko.cleanNode does not actually remove any event handlers, so it will still have the original handler.

One technique that you could use is described in this tip on knockmeout.net.

This allows you to identify an area that you want Knockout to skip binding.

You would add a simple custom binding on your section that you don't want to be bound originally:

ko.bindingHandlers.stopBinding = {
    init: function() {
        return { controlsDescendantBindings: true };
    }
};

Would be as shown in this fiddle.