2012-08-17 78 views
0

有沒有人有ViewModel中的鏈式依賴屬性的工作示例? 的代碼示例將解釋什麼我談論:KnockoutJS鏈依賴屬性

<script type="text/javascript"> 
    var ViewModel = function() { 
     this.SelectedPubCode = ko.observable('@Model.PubCode'); 
     this.SelectedVersionName = ko.observable('@Model.VersionName'); 
     this.PubCodes = ko.observable(@Model.PubCodes.ToJavascriptArray()); 
     this.VersionNames = ko.observable(@Model.VersionNames.ToJavascriptArray()); 

     this.LoadVersionNames = function(pubCode) { 
      var self = this; 
      $.ajax({ 
       type: "POST", 
       url: '@Url.Action("LoadVersionNames")', 
       data: "pubCode=" + pubCode, 
       success: function(data) { 
        self.VersionNames(data); 
        // Trigger chain call (will call SelectedVersionName subscribtion). 
        self.SelectedVersionName(''); 
       } 
      }); 
     }; 

     this.SelectedPubCode.subscribe(function(newPubCode) { 
      // Accessing public variable to call model's method 
      model.LoadVersionNames(newPubCode); 
     }); 

     this.SelectedVersionName.subscribe(function(newValue) { 
      // Another model's method can be called here. 
      alert("Version Name has been changed to '" + newValue + "'"); 
     }); 
    }; 
    // Creating public variable to access it from inside of subscribtion action 
    var model = new ViewModel(); 
    ko.applyBindings(model); 
</script> 

請看this.SelectedPubCode.subscribe(function(newPubCode)電話。我必須使用全局變量來使這個工作。 有沒有其他方法可以實現我想要的行爲?

回答

2

Knockout團隊建議在視圖模型中使用自變量來存儲此指針。在這種情況下,您可以使用self來調用LoadVersionNames函數,而不是使用全局變量。

您的代碼應如下:

<script type="text/javascript"> 
    var ViewModel = function() { 
     var self = this; 
     self.SelectedPubCode = ko.observable('@Model.PubCode'); 
     self.SelectedVersionName = ko.observable('@Model.VersionName'); 
     self.PubCodes = ko.observable(@Model.PubCodes.ToJavascriptArray()); 
     self.VersionNames = ko.observable(@Model.VersionNames.ToJavascriptArray()); 

     self.LoadVersionNames = function(pubCode) { 
      $.ajax({ 
       type: "POST", 
       url: '@Url.Action("LoadVersionNames")', 
       data: "pubCode=" + pubCode, 
       success: function(data) { 
        self.VersionNames(data); 
        // Trigger chain call (will call SelectedVersionName subscribtion). 
        self.SelectedVersionName(''); 
       } 
      }); 
     }; 

     self.SelectedPubCode.subscribe(function(newPubCode) { 
      // Accessing public variable to call model's method 
      self.LoadVersionNames(newPubCode); 
     }); 

     self.SelectedVersionName.subscribe(function(newValue) { 
      // Another model's method can be called here. 
      alert("Version Name has been changed to '" + newValue + "'"); 
     }); 
    }; 
    // Creating public variable to access it from inside of subscribtion action 
    var model = new ViewModel(); 
    ko.applyBindings(model); 
</script> 
+0

非常感謝您!我確定在訂閱通話中「自我」無法訪問。 – Anubis 2012-08-17 08:13:17