Search code examples
knockout.jsknockout-3.0knockout-3.2

Binding data synchronous or asynchronous


Are the binding functions synchronous at knockout.js? Would I get always the data in my getDeliveryNote function in this example?

function myModel(){
    var self = this;
    self.orders = ko.observable();

    self.selectAndClick = function(data){
        self.orders(data);
        self.getDeliveryNote();
    }

    self.getDeliveryNote(){
        console.log(self.orders()); // would i ALWAYS get the data here?
    }

}

Solution

  • Yes, everything will be updated synchronously. Yes, getDeliveryNote will always contain the data you set with self.orders(data);

    You could consider using a ko.computed here so that deliveryNote depends on orders, then you wouldn't need to call getDeliveryNote at all. eg.

    self.deliveryNote=ko.computed(function(){
        //...using orders() inside this function will cause 'deliveryNote'
        //...to be reevaluated when the value of 'orders' changes
        //...(ie this function will be called
        //...when orders(data) is called with a different 'data' from last time)
    
        return orders().deliveryNote() // for example
    
        });
    

    Now you can use deliveryNote() and it will always be in sync with what is in orders.

    Then you also wouldn't need the selectAndClick function because you would bind directly to orders instead.