排序Knockout在数据绑定foreach中只计算一次

时间:2018-06-18 10:30:33

标签: knockout.js computed-observable

所以这里我的问题是我想要淘汰的foreach根据每个对象的一个​​值(Order的totalTTC)以降序显示我的计算对象数组。即使订单中的totalTTC在用户更改内容时发生变化,我也不希望此订单发生变化。但每次更改时排序都会更新,我不知道如何禁用它。这是我的计算:

appViewModel.orders = ko.computed(() -> (
  orders = []
  # Check if seller of this shoppingCartLine exists
  appViewModel.shoppingCartLines().forEach((shoppingCartLine) ->
  existingOrder = null
  orders.forEach((order) ->
    if order.seller? and order.seller.id() == shoppingCartLine.ad.ownerJson.id()
      existingOrder = order
  )
  # If it exits add it to its shoppingCartLines array
  if existingOrder?
    existingOrder.shoppingCartLines.push(shoppingCartLine)
    return
  # Otherwise create a new order from this shoppingCartLine
  else
    seller = shoppingCartLine.ad.ownerJson
    shoppingCartLines = ko.observableArray([shoppingCartLine])

    order = new Order(seller, shoppingCartLines, appViewModel.freeShippingFeesThreshold)
    orders.push(order)
    return
  )
  return orders
))

这是我的HTML:

<div data-bind="foreach: {data: orders().sort(function (o, r) { return r.totalHT() > o.totalHT() ? 1 : -1 }), as: 'order'}">

我只想要一次触发排序功能。

1 个答案:

答案 0 :(得分:0)

由于您说在添加/删除订单时不需要敲除更新,并且不需要更新排序,因此订单不需要是可观察的。

我个人也在viewModel中对它进行排序。我喜欢标记包含尽可能少的代码。

  appViewModel.orders = computeOrders().sort(function (o, r) { return r.totalHT() > o.totalHT() ? 1 : -1 });

  function computeOrders() {
      # Check if seller of this shoppingCartLine exists
      appViewModel.shoppingCartLines().forEach((shoppingCartLine) ->
      existingOrder = null
      orders.forEach((order) ->
        if order.seller? and order.seller.id() == shoppingCartLine.ad.ownerJson.id()
          existingOrder = order
      )
      # If it exits add it to its shoppingCartLines array
      if existingOrder?
        existingOrder.shoppingCartLines.push(shoppingCartLine)
        return
      # Otherwise create a new order from this shoppingCartLine
      else
        seller = shoppingCartLine.ad.ownerJson
        shoppingCartLines = ko.observableArray([shoppingCartLine])

        order = new Order(seller, shoppingCartLines, appViewModel.freeShippingFeesThreshold)
        orders.push(order)
        return
      )
      return orders
  }

HTML:

<div data-bind="foreach: orders">