Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Knockout to bind different models to different sections on a page

Tags:

knockout.js

I'm using knockout javascript library in my asp.net application.

For knockout I use ko object and applyBindings() method to bind it. Now I want to bind two knockout object to two different user interface section. How can I use have second knockout object or have second datasource so I can use it in my second section?

like image 437
Mazdak Avatar asked Dec 03 '25 14:12

Mazdak


1 Answers

You can easily apply different bindings to different parts of the HTML code.

If you have a structure such as this:

<div id="one"></div>
<div id="two"></div>

Just do something like this:

ko.applyBindings(viewModelOne, document.getElementById('one'));
ko.applyBindings(viewModelTwo, document.getElementById('two'));

If you have a structure such as this:

<div id="one">
    <div id="two"></div>
</div>

You can use the controlsDescendantBindings flag to tell knockout to leave a certain child element alone. Use this in a custom binding such as the one below:

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

And use it like this:

<div id="one">
    <div data-bind="stopBinding: true">
        <div id="two"></div>
    </div>
</div>

I surrounded the 2nd div with the stopBinding function. This allows you to call the same applyBindings code like so:

ko.applyBindings(viewModelOne, document.getElementById('one'));
ko.applyBindings(viewModelTwo, document.getElementById('two'));

Reference: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

like image 88
Jensen Ching Avatar answered Dec 06 '25 15:12

Jensen Ching