filur
filur

Reputation: 1556

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?

Upvotes: 0

Views: 104

Answers (1)

Jeroen
Jeroen

Reputation: 63719

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 :-)

Upvotes: 1

Related Questions