简体   繁体   English

如何延迟绑定KnockoutJS可观察量

[英]How to late bind a KnockoutJS observable

I have a ViewModel with some observables and a property which is only known after the bindings have been applied. 我有一个带有一些observable的ViewModel和一个仅在应用绑定后才知道的属性。

For example, my UI consists of a search box which shows matches underneath. 例如,我的UI包含一个搜索框,显示下面的匹配项。 Initially, the property for the matches inside the view model is null as there is no data to attach. 最初,视图模型内匹配的属性为null,因为没有要附加的数据。 However, once the search box has at least 3 characters, it will make an AJAX call and fetch the data. 但是,一旦搜索框至少有3个字符,它将进行AJAX调用并获取数据。

When I call the mapping plugin, to map the data from the call to KO, its as if KO can't late-bind the observable array. 当我调用映射插件时,要将数据从调用映射到KO,就好像KO不能后期绑定可观察数组。 The problem is I don't have anything to give it to map to set-up the bindings in the first place. 问题是我没有任何东西可以让它映射到首先设置绑定。

My code: 我的代码:

  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]);

Once the bindings are run, KO is not able to know about any new observables that are created (other than in templating scenarios). 一旦绑定运行,KO就无法知道所创建的任何新的可观察对象(模板场景除外)。

You would want to create self.customers as an empty observable array initially, then you could allow the mapping plugin to update it. 您可能希望最初将self.customers创建为空的可观察数组,然后您可以允许映射插件更新它。

There are a couple of ways to do it, but something like this: 有几种方法可以做到这一点,但是这样的事情:

    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