简体   繁体   中英

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.

For example, my UI consists of a search box which shows matches underneath. Initially, the property for the matches inside the view model is null as there is no data to attach. However, once the search box has at least 3 characters, it will make an AJAX call and fetch the data.

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. 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).

You would want to create self.customers as an empty observable array initially, then you could allow the mapping plugin to update it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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