5

我有一个自定义绑定来处理自动完成,当用户从自动完成中选择一个项目时,我与服务器交谈并用缩短的名称替换 text_field。问题是这会再次触发我的自定义绑定的“更新”功能。

Knockout.js 代码(编辑:注意以下是 CoffeeScript):

ko.bindingHandlers.ko_autocomplete =
  init: (element, params) ->
    $(element).autocomplete(params())

  update: (element, valueAccessor, allBindingsAccessor, viewModel) ->
    unless task.name() == undefined
      $.ajax "/tasks/name",
        data: "name=" + task.name(),
        success: (data,textStatus, jqXHR) ->
          task.name(data.short_name)


  Task = ->
    @name = ko.observable()
    @name_select = (event, ui) ->
      task.name(ui.item.name)
      false  

  task = Task.new()

看法

= f.text_field :name, "data-bind" => "value: name, ko_autocomplete: { source: '/autocomplete/tasks', select: name_select }"

有没有办法对自定义绑定应用限制?

当我将 task.name 设置为从服务器发回的 short_name 时,我只想阻止自定义绑定“更新”功能再次触发。

4

2 回答 2

3

一般来说,我发现这样的模式适合我

ko.bindingHandlers.gsExample = 
    update: (element, valueAccessor, allBindingsAccessor, viewModel) ->
        args = valueAccessor()

        # Process args here, turn them into local variables
        # eg.
        span = args['span'] || 10

        render = ko.computed ->
            # Put your code in here that you want to throttle
            # Get variables from things that change very rapidly here

            # Note: You can access variables such as span in here (yay: Closures)
            some_changing_value = some_observable()

            $(element).html(some_changing_value)

        # Now, throttle the computed section (I used 0.5 seconds here)
        render.extend throttle : 500

        # Cause an immediate execution of that section, also establish a dependancy so 
        #  this outer code is re-executed when render is computed.
        render()
于 2012-05-27T00:27:09.727 回答
2

如果你不想违反隔离,那么你可以使用自动完成的延迟选项和它的选择事件,扔掉更新功能。

以这种方式修改您的init:

   var options = $.extend(params(), { 
      select: function(ev, ui) {
        var name = ui.item ? ui.item.short_name : this.value
        task.name(name);
      }
    })
   $(element).autocomplete(options)

您的更新被称为第二次,因为(为了简化)更新本身就是某种计算。所以它订阅了它内部访问的每个 observable。在这一行unless task.name() == undefined中,您订阅更新到task.name(). 然后,当您使用成功的 ajax 请求更新您的 observable 时task.name(data.short_name),更新会得到通知并重新计算。

于 2012-05-02T01:48:07.970 回答