如何手动触发bindingHandler?

时间:2013-12-04 00:18:55

标签: knockout.js

我的DOM中有以下绑定处理程序:

<textarea data-bind="value: responseText, pagedown: liveEditors['editor'], valueUpdate: 'afterkeydown'"></textarea>

绑定处理程序js:

ko.bindingHandlers.pagedown = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    // when formatting is not enabled, this will be null
    if (valueAccessor() != null) {
        valueAccessor().hooks.chain("onPreviewRefresh", function () {
            $(element).change();
        });
    }
}
};

此绑定处理程序用于向下翻页格式化。刚才,格式化默认显示,因此valueAccessor()总是被命中,因为liveEditors['editor']数组项是非空的。

但是现在,我试图阻止这个绑定处理程序运行直到满足条件 - 当用户触发“showFormatting”时,我希望这个bindingHandler重新计算,因为数组已经被填充。

目前,bindingHandler在加载时被点击一次,valueAccessor()为空(正如预期的那样 - 格式化未启用),但它永远不会被再次命中。

如何从函数中手动触发处理程序,或者在重新评估之前将其传递给观察者以进行观察?

更新:更改textarea:

 <textarea data-bind="value: responseText, pagedown: { editor: liveEditors['editor'], showFormatting: showResponseFormatting }, valueUpdate: 'afterkeydown'"></textarea>

 <a class="response-button-container" data-bind="click: showFormatting">show editor</a>

JS:

self.showFormatting = function() {
    self.showResponseFormatting(true);
    buildEditor();
    runEditor();
};
self.showResponseFormatting = ko.observable(false);

绑定处理程序:

ko.bindingHandlers.pagedown = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {

    var options = valueAccessor();
    var showFormatting = ko.unwrap(options.showFormatting);
    var editor = options.editor;


    // when formatting is not enabled, this will be null
    if (showFormatting && editor != null) {
        editor.hooks.chain("onPreviewRefresh", function () {
            $(element).change();
        });
    }
}
};

1 个答案:

答案 0 :(得分:3)

绑定处理程序的update函数将在它访问的任何observable上创建依赖关系,因为绑定在它们自己的计算可观察对象中运行。

所以,你可能想做类似的事情:

ko.bindingHandlers.pagedown = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var options = valueAccessor(),
            showFormatting = ko.unwrap(options.showFormatting),
            editor = options.editor;

        // when formatting is not enabled, this will be null
        if (showFormatting && options.editor != null) {
           options.editor.hooks.chain("onPreviewRefresh", function () {
                $(element).change();
            });
        }
    }
};

然后绑定:

data-bind="pagedown: { editor: liveEditor['editor'], showFormatting: myObservable }"

所以,我们的想法是,当编辑器准备就绪时,你可以将observable设置为true。由于其值在update函数中访问,因此绑定将在更改时再次运行。

当您不确定是否已获得普通属性或可观察属性时,

ko.unwrap是一种检索值的安全方法。