0

I have two viewModels i used in my body tag, to control 2 separate divs, i am trying to pass a value to the second view models observable function, but it doesn't seem to work. it even possible to make two view models interact ?

this is the code:

   function friendsOnlineModel(data,mapping) {

    //saveUserDetailsOffline(data.user);

    onlineFriends = ko.mapping.fromJS(data,mapping);


    onlineFriends.startChat = function() {


        new chatModel().username("olu");

    };

    onlineFriends.sending_message = ko.observable("");

    return onlineFriends;
}

function chatModel() {

   var chat = this;

   chat.username = ko.observable('kunle');

   return chat;

}
appzone_oto
  • 333
  • 1
  • 4
  • 16
  • Possible duplicate of [Knockout Passing Value between two view models](https://stackoverflow.com/questions/22091846/knockout-passing-value-between-two-view-models) – Jason Spake May 22 '18 at 16:28
  • Here's another good resource: http://www.wrapcode.com/communication-between-multiple-view-models-in-knockoutjs-mvvm-the-right-approach/ – Jason Spake May 22 '18 at 16:28

1 Answers1

0

Do not confuse knockout with black magic. Of course they can intercat, an observable is nothing more than a simple javascript function, so given that you hold a reference to it you can pass it anywhere you like. To do so you should initialize your viewModels and hold a reference to them. i.e: if you want your "friendsOnlineModel" to communicate with your chatModel, you should define the dependency among them, who needs who, who should be pass as a parameter to whom.

So in essence you could do something like this:

   function friendsOnlineModel(data,mapping,chatModel) {

    //saveUserDetailsOffline(data.user);

    onlineFriends = ko.mapping.fromJS(data,mapping);


    onlineFriends.startChat = function(userName) {
        chatModel.username(userName);

    };

    onlineFriends.sending_message = ko.observable("");

    return onlineFriends;
}

function chatModel() {

   var chat = this;

   chat.username = ko.observable('kunle');

   return chat;

}

var chatModel = new chatModel();
var friendsOnModel = new friendsOnlineModel(data,mapping,chatModel);

Let me know if this helps!

MKougiouris
  • 2,821
  • 1
  • 16
  • 19