Search code examples
jqueryajaxknockout.jsknockout-3.0

knockout multiple ajax calls


Following code does multiple ajax calls. I'd like only one call actually.

        var update = function(){

        if(self.origin() && self.destination()){

            // AJAX CALL HERE
            $.get(something);

        }
    }


    self.origin.subscribe(function() {
        update(false);
    });

    self.destination.subscribe(function() {
        update(false);
    });

    self.origindatetime.subscribe(function() {
        update(true);
    });

    self.returndatetime.subscribe(function() {
        update(true);
    });

I tried deferred updates. But no luck.

How can i avoid multiple ajax calls?


Solution

  • Instead of individually subscribing to each observable, consider using a computed observable and only make the ajax call when all your parameters are as desired (see Example: Avoiding multiple Ajax requests at http://knockoutjs.com/documentation/deferred-updates.html).

    The following is based on that example:

    function ViewModel() {
        this.origin = ko.observable();
        this.destination = ko.observable();
        ko.computed(function() {
            var params = { origin: this.origin(), destination: this.destination() };
                if (params.origin && params.destination) {
                    $.get(something);
                }
        }, this).extend({ deferred: true });
    }
    

    The computed observable will evaluate when your view model is instantiated and then whenever origin or destination changes.

    The deferred extension only assures that if you, for some reason, update both origin and destination at once (e.g. in another function) the computed observable will only be evaluated once.