I am working with Knockout for the first time and I am struggling with an observable. I have declared it in one view model and I need to gain access to the value in another. Any tips on how to go about that?
First declare your 1st model in a shared scope, then the 2nd. If you do something like myfirstmodel.myobservable()
within your second model, you should see it and interact with it.
var myModel = whatever();
var mySndModel = whateverElse();
ko.applyBindings(myModel, document.getElementById('whatever'))
ko.applyBindings(mySndModel, document.getElementById('whateverElse'))
whateverElse
is the constructor of your second model, in which you can call myModel.myObservable()
What you have to do, it's to inherit the parentViewModel
function parentViewModel() {
// Just a best practice potato here :P
var self = this;
// Initialize the childViewModel change it's 'this'
childViewModel.call(self);
self.observable = ko.observable();
}
function childViewModel() {
var self = this;
console.log(self); // It will output the parentViewModel scope
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.