繁体   English   中英

如何延迟绑定KnockoutJS可观察量

[英]How to late bind a KnockoutJS observable

我有一个带有一些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]);

一旦绑定运行,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);
            });
        } 
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM