我有一个带有一些observable的ViewModel和一个仅在应用了绑定后才知道的属性。
例如,我的用户界面包含一个搜索框,其中显示了下方的匹配项。最初,视图模型内匹配的属性为null,因为没有要附加的数据。但是,一旦搜索框至少有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]);
答案 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);
});
}
});