我想将数据发送到另一个淘汰视图模型。 例如,用户转到包含项目列表的页面。然后每个项目,有一个链接。如果用户单击该链接,则下一页将具有该值。对于列表项是3号。下一页将有3作为值..
我对此感到畏惧但却失败了
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);
};
和另一个模型,
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;
}
});
};
答案 0 :(得分:1)
其中一种简单的方法是在主视图模型中创建第二个视图模型的新实例作为可观察变量,然后您可以轻松地在视图模型之间进行通信。
下面我只是向您展示可以使用的逻辑。
示例: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);