gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:14:22 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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

关于Knockout.js - 如何限制自定义绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10406269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com