在knockout中扩展文本绑定

Extend text binding in knockout

本文关键字:文本 绑定 扩展 knockout      更新时间:2023-09-26

是否有可能通过其他选项扩展敲除中的text结合?例如:

ko.bindingHandlers.text = {
    update: function(element, valueAccessor, allBindingsAccessor){
        var options = allBindingsAccessor().textOptions || {};
        options = _.extend({
            'required': false
        }, options);
        if(options['required']){
            // Do some required things
        }
    }
};

那么一个文本绑定可以写成:

<span data-bind="text: myText, textOptions: { required: true }" />

这是可能的还是需要自定义绑定?

关于包装现有绑定,请参阅这里的第3节。要点是,在init部分,您调用ko.bindingHandlers.text.init, update也类似。在这些电话中,你可以做任何你喜欢的事情。如果你包装的绑定没有init或update,你会得到一个错误,你可以删除那个调用。

嗯,这不是扩展 text绑定,而是覆盖了

首先,请注意当前text绑定非常简单。摘自原文:

ko.bindingHandlers['text'] = {
    'init': function() {
        // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
        // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
        return { 'controlsDescendantBindings': true };
    },
    'update': function (element, valueAccessor) {
        ko.utils.setTextContent(element, valueAccessor());
    }
};

实际的功能被卸载到setTextContent,它处理跨浏览器设置,嗯,文本内容。

如果您想要一个与text类似的绑定,只是添加了一些特性,那么最简单的方法可能是自己创建一个使用setTextContent的自定义绑定处理程序。例如:

ko.bindingHandlers['myText'] = {
    'init': function() {
        return { 'controlsDescendantBindings': true };
    },
    'update': function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor()), txt = '';
        if (value !== null && typeof value == "object") {
            txt = value['text'];
            if (!!value['required']) { txt += "!!!"; }
          
        } else {
            txt = value;
        }
        ko.utils.setTextContent(element, txt);
    }
};
ko.applyBindings({ testProperty: "test text 1234" });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js"></script>
<span data-bind="myText: { text: testProperty, required: true }"></span>
<br>
<span data-bind="myText: { text: testProperty, required: false }"></span>
<br>
<span data-bind="myText: testProperty"></span>