knockout.punches icon indicating copy to clipboard operation
knockout.punches copied to clipboard

Access current bindingContext in filters - is it possible to do this?

Open helmut-hoffer-von-ankershoffen opened this issue 10 years ago • 1 comments

Background: we built a "trans" (translation) filter - that actually uses translation messages of a Symfony2 backend - and can be used e.g. like so:

{{ 'translate-this' | trans : 'translation-domain' }}

We want to be able to set the default translation domain like so {{# transDefaultDomain: 'whatever' }} {{ 'translate-this' | trans }} {{ 'and-this' | trans }} {{/ transDefaultDomain }}

so that for multiple translations the domain has not to be given per element ...

Therefore our trans-filter needs to access the current binding context ...

Best Regards

P.S.: We love your extension.

I'm hesitant to pass in the binding context or any other fixed parameters mainly because I'd like to keep the filter interface simple.

Another idea that could help is to support a per-filter preprocesor. Then you could set up something like the following:

ko.filter.trans.preprocess = function (arguments) {
    return arguments || "$context.domain";
}

For now, you can add a preprocessor function to the text binding that adds the parameter:

ko.punches.utils.addBindingPreprocessor('text', function (input) {
    return input.replace(/\| *trans/, "| trans:$context.domain");
});

(My example isn't very robust. It'll break instances of a filter that begins with "trans" or where "trans" is specified with an argument.)

mbest avatar Aug 25 '14 10:08 mbest