applyBindings twice for separate DOM objects, fails.

310 views
Skip to first unread message

Craig Lister

unread,
Nov 21, 2016, 5:22:27 AM11/21/16
to KnockoutJS

I have an MVC application which has a content page, linked to a view model. It works well. But as soon as I add a view model to my content page (Generated within my layout), I get the error:

You cannot apply bindings multiple times to the same element.

I have created 'Sections' and try to bind to that section, as shown below.

// In my Layout page.


<div class='liveExample' id="sectionOne">   
    <p>First name: <input data-bind='value: firstName' /></p> 
    <p>Last name: <input data-bind='value: lastName' /></p> 
    <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>  
</div>

// In my Index (content) page.

<div class='liveExample' id="sectionTwo">   
    <p>First name: <input data-bind='value: firstName' /></p> 
    <p>Last name: <input data-bind='value: lastName' /></p> 
    <h2>Hello, <span data-bind='text: fullName'> </span>!</h2>  
</div>


And the code:

// In my _Layout page: ko.applyBindings(new ViewModel1("Planet", "Earth"), $("#sectionOne")[0]); // This makes Knockout get to work

// In my Index page: ko.applyBindings(new ViewModel2("Planet", "Earth"), $("#sectionTwo")[0]); // This makes Knockout get to work


Here's a jsfiddle

https://jsfiddle.net/4fe2f6mL/1/


I can't create a main view model, with the two models above as child views, as the ko.applyBindings is on separate cshtml files.

How can I get this to work, as I have a viewmodel for my Layout (Drives the menu, login, registration and "Welcome, Username" type stuff in the navbar)

Michael Best

unread,
Nov 21, 2016, 5:29:58 PM11/21/16
to KnockoutJS
The fiddle merely helps show that it works fine: https://jsfiddle.net/4fe2f6mL/2/

-- Michael
Reply all
Reply to author
Forward
0 new messages