Knockout.js - 如何限制自定义绑定

map*_*ap7 5 knockout.js ko-custom-binding

我有一个自定义绑定来处理自动完成,当用户从自动完成中选择一个项目时,我会与服务器通信并用缩短的名称替换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()
Run Code Online (Sandbox Code Playgroud)

视图

= f.text_field :name, "data-bind" => "value: name, ko_autocomplete: { source: '/autocomplete/tasks', select: name_select }"
Run Code Online (Sandbox Code Playgroud)

有没有办法将油门应用于自定义绑定?

我只想在将task.name设置为从服务器发回的short_name时再次触发自定义绑定'更新'功能.

Tom*_*eys 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()
Run Code Online (Sandbox Code Playgroud)

  • 添加 disposeWhenNodeIsRemoved 选项以允许正确处理新的计算绑定非常重要,否则会出现内存泄漏和性能下降或更糟的情况。 (2认同)