【问题标题】:What is Knockout custom binding "after" variable?什么是 Knockout 自定义绑定“之后”变量?
【发布时间】:2017-04-22 10:45:29
【问题描述】:

我在某些项目中使用 knockoutASP.NET MVC
我正在使用以下bindingHandler的淘汰赛

ko.bindingHandlers.select2 = {
    after: ["options", "value", "selectedOptions"],
    init: function (el, valueAccessor, allBindingsAccessor, viewModel) {
        // no explicit reference to the 'after' variable
    },
    update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
        // no explicit reference to the 'after' variable
    }
}

我从this question 获得了这段代码,并对其进行了少许修改。
Select2 plugin 基本上是一个custom binding handler

问题
我只想知道after: ["options", "value", "selectedOptions"], 在这里是什么意思。在initupdate 函数中的任何地方都没有对此变量的引用。
这个变量在这种情况下有什么意义吗?或者这是一个淘汰指令,使其在完成执行 [options, value, selectedOptions] 绑定后执行此自定义绑定?

注意 custom binding 的文档没有提到这个变量。

【问题讨论】:

    标签: knockout.js ko-custom-binding


    【解决方案1】:

    你说得对,它似乎没有记录。深入了解KO source code 向我们展示了这一点:

    // First add dependencies (if any) of the current binding
    if (binding['after']) {
        cyclicDependencyStack.push(bindingKey);
        ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
            if (bindings[bindingDependencyKey]) {
                if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
                    throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
                } else {
                    pushBinding(bindingDependencyKey);
                }
            }
        });
        cyclicDependencyStack.length--;
    }
    

    您的假设似乎是正确的。 KO 正在构建一个必须在当前绑定运行之前运行的依赖绑定列表。内置的valueselectedOptions 绑定利用了这个关键字。

    这里是discussion on implementation from the Knockout Github

    这是一个相关的StackOverflow answer

    请参阅该答案中的 JSFiddle 以获取示例代码。

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2014-12-31
      • 1970-01-01
      • 2017-09-15
      • 2015-06-21
      相关资源
      最近更新 更多