javascript - observe KO observable from another viewmodel -
so have 2 view models taking each other
var viewmodel1 = function(){ this.messageforvm2 = ko.observable(""); this.message = ko.observable("hello vm1") }; var viewmodel2 = function(vm1){ this.message = ko.observable(vm1.messageforvm2()); }; var mastervm = (function(){ this.viewmodel1 = new viewmodel1(), this.viewmodel2 = new viewmodel2(this.viewmodel1); })(); ko.applybindings(mastervm)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <h4>view model 1</h4> <div data-bind="with: viewmodel1"> <p data-bind="text: messageforvm2"></p> <input data-bind="value: messageforvm2, valueupdate: 'input'" /> </div> <h4>view model 2</h4> <div data-bind="with: viewmodel2"> <!-- ko if: message() === "hello" --> <p data-bind="text:message"></p> <!-- /ko --> </div>
(also on here http://jsfiddle.net/ceryb9pc/)
i want viewmodel2 data-bind show if "hello" value in observable in viewmodel1. works want work when value updated in viewmodel1 input.
in example works when:
this.messageforvm2 = ko.observable("hello");
but need remove like:
this.messageforvm2 = ko.observable();
you need assign first viewmodel's observable second viewmodel's message
variable. otherwise set first time loads.
change:
this.message = ko.observable(vm1.messageforvm2());
to:
this.message = vm1.messageforvm2;
this way, this.message
reference vm1.messageforvm2
, meaning both variables share same value.
var viewmodel1 = function(){ this.messageforvm2 = ko.observable(""); this.message = ko.observable("hello vm1") }; var viewmodel2 = function(vm1){ this.message = vm1.messageforvm2; }; var mastervm = (function(){ this.viewmodel1 = new viewmodel1(), this.viewmodel2 = new viewmodel2(this.viewmodel1); })(); ko.applybindings(mastervm)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <h4>view model 1</h4> <div data-bind="with: viewmodel1"> <p data-bind="text: messageforvm2"></p> <input data-bind="value: messageforvm2, valueupdate: 'input'" placeholder="enter 'hello' here" /> </div> <h4>view model 2</h4> <div data-bind="with: viewmodel2"> <!-- ko if: message() === "hello" --> <p data-bind="text:message"></p> <!-- /ko --> </div>
Comments
Post a Comment