TwoWay Binding initializer

Nov 14, 2015 at 3:33 PM
Edited Nov 14, 2015 at 3:36 PM
I've finally figured out how to use the binding initializers and your framework works so much better with these. I modified a sample that was provided by Philip Japikse. Instead of changing the datacontext property directly, this initializer modifies the property on the viewmodel through its setter. That way, the ViewModelBase's raisePropertyChanged function changes the dataContext property instead and you can add your own logic to the changed value. This initializer only works with the onchange event, but you can probably make others very easily. Thought this would be of interest to anyone who might use your framework.
module BindingInitializers {

    export var getDestinationValue: Function = (dest, destProps) => {
        if (destProps.length === 1) {
            return dest[destProps[0]];
        }
        else {
            var element = eval("dest['" +
                destProps.slice(0, destProps.length - 1).join("']['") + "']");
            return element[destProps[destProps.length - 1]];
        }
    };

    export var getSourceObject: Function = (source, sourceProps) => {
        if (sourceProps.length === 1) {
            return source;
        }
        else {
            return eval("source['" + sourceProps.slice(0, sourceProps.length - 1).join("']['") + "']");
        }
    };


    export var twowaychange: Function = WinJS.Binding.initializer((source, sourceProps: string[], dest, destProps: string[]) => {
        dest.onchange = () => {
            var newValue = BindingInitializers.getDestinationValue(dest, destProps);
            var targetObject = BindingInitializers.getSourceObject(source, sourceProps);
            var oldValue = targetObject[sourceProps[sourceProps.length - 1]];

            if (oldValue !== newValue) {
                //targetObject[sourceProps[sourceProps.length - 1]] = newValue;
                source[sourceProps[sourceProps.length - 1]] = newValue;
            }
        };

        return WinJS.Binding.defaultBind(source, sourceProps, dest, destProps);
    });

}
Use this way:
<input class="win-textbox" data-win-bind="value: dataContext.saveDescription BindingInitializers.twowaychange"/>
Coordinator
Nov 14, 2015 at 3:46 PM
Thank you, Lee!