mbest / knockout

My enhancements to Knockout
35 stars 4 forks source link

allow binding handlers to pre-process bindings #18

Open mbest opened 12 years ago

mbest commented 12 years ago

insertPropertyAccessors already does some pre-processing, but it may make sense to move this to the binding handlers. They would have a function that takes a value string and returns a new value string.

I was thinking of this in the context of SteveSanderson/knockout/#388 where it would be cool to be able to have something like foreach: $wizardStep in steps that would be translated to foreach: {data: steps, itemName: '$wizardStep'}.

mbest commented 12 years ago

It might be useful to have the pre-processor also be able to change the binding key (or have a different pre-processor function). For example, with: $wizard = myWizard could be changed to template: {if: myWizard, data: myWizard, dataName: '$wizard'}

vamp commented 12 years ago

if 'click' binding added later (e.g. using ko.conventions), preprocess not working at all

mbest commented 12 years ago

Good catch. I hadn't thought of that. Where can I find ko.conventions?

vamp commented 12 years ago

check this: http://blog.stevensanderson.com/2011/12/21/knockout-2-0-0-released/ section: 5. Binding providers (and hence external bindings) or fiddle: http://jsfiddle.net/StevenSanderson/2eY2u/

mbest commented 12 years ago

Thanks.

mbest commented 12 years ago

My current idea is that the preprocess function can return either a string, to replace the value of the current binding, or return an array, to replace or add to the current binding. The array will contain one or more key/value pairs as two-element arrays:

[
    [ 'key1', 'value1' ],
    [ 'key2', 'value2' ]
]

The function is passed two parameters: value and key, both strings.

mbest commented 12 years ago

One issue to address is that new bindings that are added by preprocess need to be at the root level but won't be currently if preprocess is called from the second level of a two-level binding.

I also had another idea for the preprocess interface. It could return either a string value, to replace the current binding, or undefined (a falsy value), to skip the current binding. A third parameter would be a callback function to add new bindings:

preprocess: function(value, key, addBinding) {
    ...
    addBinding('key1', 'value1');
    addBinding('key2', 'value2');
}