Reputation: 994
I want to send data to another knockout view model. For example, A user go to a page with list of items. Then per item, there is a link. If the user click the link, The next page will have the value for example. for the list item is number 3. the next page will have 3 as value..
I treid this but failed
methods.initialize = function() {
var self = this;
self.setupSubscriptions();
self.update(true);
Utils.ajaxPost('getMyOrganizations',{"data":""},function(result){
result = JSON.parse(result);
if(_.isArray(result)){
_.each(result,function(obj){
self.organizations.push([obj["organization_name"],3,3,obj['id']]);
});
}
});
};
methods.setupSubscriptions = function() {
var self = this;
self.update.syncWith('selectedOrg',true);
};
and the other model,
methods.initialize = function() {
var self = this;
self.setupSubscriptions();
};
methods.setupSubscriptions = function() {
var self = this;
self.update.subscribeTo('selectedOrg', function(newUser){
if(newUser){
//Do the logic here
self.update = true;
}
});
};
Upvotes: 0
Views: 77
Reputation: 3654
One of the easy ways is to create a new instance of your second view model inside your main View Model as an observable variable and then you can easily communicate between your view models.
Below I am just showing you the logic you can use.
Example :https://jsfiddle.net/kyr6w2x3/67/
HTML:
<ul data-bind="foreach:Items">
<li>
<span data-bind="text:item">
</span>
<a data-bind="click:$parent.LinkClicked,text:'ClickOnME'">
</a>
</li>
</ul>
<div data-bind="text:MessageFromSecondVM">
</div>
<hr>
<div data-bind="with:SecondVM">
<h3 data-bind="text:SecondVMVariable">
</h3>
</div>
JS:
function FirstViewModel() {
var self = this;
self.SecondVM = ko.observable();
self.FirstVMVariable = ko.observable();
self.MessageFromSecondVM = ko.observable();
self.Items = ko.observableArray([{item:"Item 1" ,value :1},{item:"Item 2" ,value :2},{item:"Item 3" ,value :3}]);
// you can create a new instance whenever you want in your model
self.SecondVM(new SecondViewModel());
self.LinkClicked = function(item){
self.SecondVM().SecondVMVariable("Value " + item.value + " sent to SecondVM From FirstVM");
self.SecondVM().Value(item.value);
}
}
function SecondViewModel() {
var self = this;
self.SecondVMVariable = ko.observable();
self.Value = ko.observable();
self.Value.subscribe(function(newValue){
if(newValue){
FirstVM.MessageFromSecondVM("Value " + newValue + " was sent back from SecondVM here");
}
})
}
var FirstVM = new FirstViewModel()
ko.applyBindings(FirstVM);
Upvotes: 1