How to pass value from one view model to another viewmodel in knockout js?

前端 未结 3 958
不思量自难忘°
不思量自难忘° 2021-01-22 00:51

i have two view models and i want to pass value from one view model to another viewmodel. i have two viewmodels and two div i want to display another div on click of button whic

3条回答
  •  时光取名叫无心
    2021-01-22 01:09

    You can make use of KO.postbox by the great @RyanNiemeyer

    I introduced one variable in both the viewmodels each

    In viewmodel 1 which will publish (shout) the changes once made :

    self.isVisible = ko.observable(false).publishOn("showDiv");
    

    in viewmodel 2 which will be listning to changes from viewmodel 1

    self.isVisible = ko.observable(false).subscribeTo("showDiv");
    

    Then I created one click method in first viewModel to toggle Show Div action (visible : true / false)

    self.showDiv = function(){
         if(self.isVisible())
             self.isVisible(false);
        else
            self.isVisible(true);
    }
    

    Changed visible binding from your existing markup to this :

    It now publish changes made in first viewmodel to second viewmodel. This is called pub-sub mechanism. Read more on : https://github.com/rniemeyer/knockout-postbox

    Fiddle here : http://jsfiddle.net/rahulrulez/0454h205/1/

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题