【问题标题】:Binding data synchronous or asynchronous同步或异步绑定数据
【发布时间】:2015-12-08 07:02:16
【问题描述】:

knockout.js 中的绑定函数是否同步? 在这个例子中,我是否总是能在我的 getDeliveryNote 函数中获得数据?

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?
    }

}

【问题讨论】:

  • 是的。是什么让您相信这行不通?
  • @CrimsonChris 只是想确保它们是同步调用。

标签: knockout.js knockout-3.0 knockout-3.2


【解决方案1】:

是的,所有内容都会同步更新。是的,getDeliveryNote 将始终包含您使用self.orders(data); 设置的数据

您可以考虑在此处使用ko.computed,以便deliveryNote 依赖于orders,那么您根本不需要调用getDeliveryNote。 例如。

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

    });

现在您可以使用deliveryNote(),它将始终与订单中的内容同步。

那么您也不需要selectAndClick 函数,因为您将直接绑定到orders

【讨论】:

  • 太棒了! :) 谢谢。
猜你喜欢
  • 2020-05-12
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
相关资源
最近更新 更多