3

我有一個ViewModel與一些observables和一個屬性,只有綁定已被應用後才知道。如何延遲綁定KnockoutJS可觀察到

例如,我的用戶界面由一個顯示下方匹配的搜索框組成。最初,視圖模型內的匹配屬性爲空,因爲沒有要附加的數據。但是,一旦搜索框至少有3個字符,它將進行AJAX調用並獲取數據。

當我調用映射插件時,將調用中的數據映射到KO,就好像KO不能將可觀察數組綁定在一起。問題是我沒有任何東西可以給它映射,以便首先設置綁定。

我的代碼:

var vm = new function() { 
     var self = this; 

     self.customers = null; 
     self.searchText = ko.observable(""); 

     self.searchText.subscribe(function (data) { 
      if (data.length > 2) { 
       // do search 
       $.get("/customers/getall", { searchTerms: self.searchText }, function (resp) { 

        if (!self.customers) { 
         // first mapping 
         self.customers= ko.mapping.fromJS(resp.customers); 
        } else { 
         ko.mapping.fromJS(self.customers, resp.customers); 
        } 
       }); 
      } 
     }); 

    } 

    ko.applyBindings(vm, $("#searchCustomersScope")[0]); 

回答

2

一旦綁定運行,KO無法知道所創建的任何新的觀測(比模板的情況除外)。

您最初想創建self.customers作爲空的可觀察數組,然後您可以允許映射插件更新它。

有幾個方法可以做到這一點,但這樣的事情:

self.customers = ko.observableArray(); 
    self.searchText = ko.observable(""); 

    self.searchText.subscribe(function (data) { 
     if (data.length > 2) { 
      // do search 
      $.get("/customers/getall", { searchTerms: self.searchText }, function (resp) { 
        ko.mapping.fromJS(resp.customers, {}, self.customers); 
      }); 
     } 
    }); 
+0

好,謝謝。我是否真的需要映射調用中的{}? – jaffa 2012-07-25 16:25:31

+0

是的,除非您從映射插件創建原始的observableArray,那麼您需要傳遞選項(在您的情況下爲空)。 – 2012-07-25 16:46:14