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