首页 文章

如何延迟绑定KnockoutJS可观察量

提问于
浏览
3

我有一个带有一些observable的ViewModel和一个仅在应用绑定后才知道的属性 .

例如,我的UI包含一个搜索框,显示下面的匹配项 . 最初,视图模型内匹配的属性为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]);

1 回答

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

相关问题