简体   繁体   English

使用自定义绑定更新元素文本

[英]Update element text using custom binding

I'm making my first custom binding. 我正在进行第一个自定义绑定。 I would like to be able to specify what text that appears on an element based on a resource file. 我希望能够指定基于资源文件在元素上显示的文本。 Something like this: 像这样:

var exampleResource = {
    hello: 'world'
};

ko.bindingHandlers.resource = {

    init: function (element, valueAccessor) {

        var value = valueAccessor();

        ko.bindingHandlers.text.update(element, function() { 
            return exampleResource[value] || '';
        });
    }

};

<span data-bind="resource: 'hello'"></span>

Should I use ko.bindingHandlers.text as above? 我应该如上所述使用ko.bindingHandlers.text吗?

Since the resource variable isn't observable, is there any point of adding the update callback for the binding? 由于无法观察到资源变量,是否有必要为绑定添加update回调? If I understand it correctly it will only get called if an observable is passed as the value? 如果我正确理解它,则仅当将observable作为值传递时才调用它?

You'd need an update if you want to support the input for your binding handler to be dynamic. 如果要支持绑定处理程序动态输入,则需要update In your example you don't do that, but you could . 在您的示例中,您没有这样做,但是可以 Here's an example: 这是一个例子:

 var exampleResource = { hello: 'world', goodbye: 'drowl' }; ko.bindingHandlers.resource = { update: function (element, valueAccessor) { var key = ko.utils.unwrapObservable(valueAccessor()); ko.bindingHandlers.text.update(element, function() { return exampleResource[key] || key; }); } }; ko.applyBindings({ myObs: ko.observable('goodbye') }); 
 span { font-weight: bold; color: red; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script> Static: <span data-bind="resource: 'hello'"></span> <hr> Dynamic: <span data-bind="resource: myObs"></span> - based on: <select data-bind="value: myObs, options: ['hello', 'goodbye']"></select> 

If you don't need this dynamicness you could stick to your old solution. 如果您不需要这种动态性,则可以坚持使用旧的解决方案。 However, in that case I'd question the added value of KnockoutJS for resources in general :-) 但是,在那种情况下,我会质疑KnockoutJS对于一般资源的附加价值:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM