2016-08-27 65 views
0

我想發送數據到另一個挖空視圖模型。 例如,用戶轉到包含項目列表的頁面。然後每個項目都有一個鏈接。如果用戶點擊鏈接,則下一頁將具有該值。列表項目編號爲3下一頁將有3個爲價值..如何發送數據到另一個淘汰賽模型?

我TREID這一點,但未能

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; 
     } 
    }); 
}; 

回答

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);