marekpw
marekpw

Reputation: 712

Aurelia bindable value converters (boolean etc.)

I have this property decorator, which runs the property value through a converter, so I can use some-bindable-value="true" inside the view template:

function valueConverter(converter: Function) {
    return (target: any, key: string) => {


        let definition = Object.getOwnPropertyDescriptor(target, key);
        if (definition) {
            Object.defineProperty(target, key, {
                get: definition.get,
                set: newValue => {
                    definition.set(converter(newValue));
                },
                enumerable: true,
                configurable: true
            });
        } else {
            Object.defineProperty(target, key, {
                get: function () {
                    return this['__' + key];
                },
                set: function (newValue) {
                    this['__' + key] = converter(newValue);
                },
                enumerable: true,
                configurable: true
            });
        }
    }
}

class App {
    @valueConverter(value => value == 'true') public someBooleanValue;

    constructor() {
        this.someBooleanValue = 'false';
        console.log(this.someBooleanValue) // false

        this.someBooleanValue = 'true';
        console.log(this.someBooleanValue) // true
    }

}

This works fine as long as I don't also use the @bindable decorator (which makes it completely pointless). I'm new to decorators and am not sure how to make this work with Aurelia's property observing mechanisms.

Upvotes: 1

Views: 586

Answers (1)

Ashley Grant
Ashley Grant

Reputation: 10887

I think if I were trying to accomplish this, I start by copying the code for the bindable decorator, and then add my own code to it. It's located here: https://github.com/aurelia/templating/blob/master/src/decorators.js

It also might be helpful to look at how the observable decorator does things: https://github.com/aurelia/binding/blob/master/src/decorator-observable.js

It looks like you might have to get your hands pretty dirty to accomplish what you want.. That being said, if you are able to make it happen, we'd love for it to come back to the framework as a PR at some point!

Upvotes: 1

Related Questions