Richard Banks
Richard Banks

Reputation: 2983

How to handle method naming conflicts in viewmodels when using knockout

brand new to knockout and was wondering whether anyone could answer a question for me.

Is there a way to handle viewmodels with properties that are named the same when binding to elements on a page. e.g

<input data-bind="value: prop1" />

function vm1(){
  this.prop1 = something
}

function vm2(){
  this.prop1 = something
}

ko.applybindings(new vm1());
ko.applybindings(new vm2());

ive tested this scenero on a textbox and basically the last binding wins. how can this scenerio get handled.

Upvotes: 1

Views: 76

Answers (2)

Chris Diver
Chris Diver

Reputation: 19842

There you are binding to the page, so the last one wins, but you instead can bind a element or section of a page by passing the element in as the second argument.

<div id="one">
  <input data-bind="value: prop1" />
</div> 

<div id="two">
  <input data-bind="value: prop1" />
</div>

function vm1(){
  this.prop1 = something
}

function vm2(){
  this.prop1 = something
}

ko.applybindings(new vm1(), document.getElementById("one"));
ko.applybindings(new vm2(), document.getElementById("two"));

Upvotes: 1

user247702
user247702

Reputation: 24222

There are two ways to solve this.

  • specify the target of your binding, like this: ko.applyBindings(new vm1(), document.getElementById("vm1"));
  • create a "master" viewmodel that holds your vm1 and vm2 models and specify the binding context

Upvotes: 1

Related Questions