简体   繁体   中英

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?

Since the resource variable isn't observable, is there any point of adding the update callback for the binding? If I understand it correctly it will only get called if an observable is passed as the value?

You'd need an update if you want to support the input for your binding handler to be dynamic. 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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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