I have two nested div and 2 button inside each div:
<div id="d1">
<button data-bind="click:x">
invoke x
</button>
<div id="d2">
<button id="Q_btn" data-bind="click:x">
invoke x
</button>
</div>
</div>
and 2 view model that binding as:
var viewModel1 = {
x : function() {
alert('from model1')
}
}
var viewModel2 = {
x : function() {
alert('from model2')
}
}
ko.applyBindings(viewModel2, document.getElementById('d2'));
ko.applyBindings(viewModel1, document.getElementById('d1'));
Now when i click on button inside d2 (Q_btn), 2 alert raise, the first one says ‘from mode2’ and the second one says ‘from model1’.
i want when i click on Q_btn only the first alert happen.
Note: in my project i load some html page on divs. each div has own view model. til now everythings are OK (each div work with own viewmodel and no conflict happen) but in case of nested div the above problem were occurred.
i appreciate your help
I don’t think that there’s any way of doing what you want in the way that you are suggesting. I’d recommend that you look at implementing a publisher/subscriber pattern here, either rolling your own (using something like jquery.pubsub), or there’s an extension called knockout-postbox you could use.
This would enable you to have your view models nicely decoupled, yet allow them to talk to each other.