Knockout.js - how do I block user bindings

I have a custom binding for autocomplete processing, and when a user selects an element from autocomplete, I communicate with the server and replace the text field with the abbreviated name. The problem is that the second time it calls the "update" function of my user binding.

Knockout.js code (edit: note the following: 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()

View

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

Is there a way to apply a choke to user binding?

I just want the "update" function of custom bindings to run the second time I set task.name to the short name sent from the server.

+5
source share
2 answers

, , ,

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()
+3

, , .

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)

, ( ) . , . unless task.name() == undefined task.name(). , task.name(data.short_name) ajax, .

+2

All Articles