Rahul
Rahul

Reputation: 5774

Can not update observable of one viewModel from another

I want to update one observable of one viewModel from another. The value gets changed but it does not reflect on UI (in HTML)

I am not sure what's wrong with the code..

Here is the code :

http://jsfiddle.net/rahulrulez/RSL4u/2/

<p data-bind="text: name"></p>

does not gets updated.

Upvotes: 0

Views: 390

Answers (3)

Rahul
Rahul

Reputation: 5774

I tried all your approaches, for some reason they were not really working with the solution I have.

After a lot of googling and digging deep in KnockoutJS documentations and extensions, I found Knockout Postbox which lets us sync or communicate between multiple irrelevant View Models.

https://github.com/rniemeyer/knockout-postbox

Here is snippet of my demo example...

var viewModel1 = function(){
   var _self = this;
   _self.name = ko.observable("Rahul").syncWith("syncedName");
}

var viewModel2 = function(){
   var _self = this;
   _self.firstName = ko.observable("Rahul").syncWith("syncedName");

}

ko.applyBindings(new viewModel1(), document.getElementById("div1"));
ko.applyBindings(new viewModel1(), document.getElementById("div2"));

Both the observable are in sync now.. I found this much better than nesting objects.. At least it satisfied the need of my application..

Thank you so much for help anyway..

My Demo : JSFiddle : http://jsfiddle.net/rahulrulez/2kuSh/1/

I hope it helped..

Thank you so much,

Rahul Patil.

Upvotes: 0

Anders
Anders

Reputation: 17554

You have two different instances of the VM2 ViewModel. Instead do

http://jsfiddle.net/RSL4u/4/

I have made VM2 a sub model of VM1

this.vm2Object = new viewModel2();

Upvotes: 1

nemesv
nemesv

Reputation: 139758

You are binding to two independent view-model instances

ko.applyBindings(new viewModel1(), document.getElementById("firstViewModel"));
ko.applyBindings(new viewModel2(), document.getElementById("secondViewModel"));

So there is no connection between your viewModel1 and viewModel2 and when you write in your viewModel1:

var vm2Object = new viewModel2();

then you are creating a completly new viewModel2 instance which has nothing to do with the one used in the applyBindings.

To fix this you need to make a connection between your view models, somehow like this (there are multiple other ways to do like using a container view model, nest your view models to each other, etc.):

var viewModel1 = function(vm2){
   var self = this;
   var vm2Object = vm2; //use vm from parameter
   //...
}

And when calling the applyBindings:

var vm2 = new viewModel2();
ko.applyBindings(new viewModel1(vm2), document.getElementById("firstViewModel"));
ko.applyBindings(vm2, document.getElementById("secondViewModel"));

Demo JSFiddle.

Upvotes: 2

Related Questions