rniemeyer / knockout-classBindingProvider

An alternate binding provider for Knockout that allows you to define your bindings in a JavaScript object and key into it from the markup.
MIT License
101 stars 27 forks source link

Support for custom elements #21

Open johndelrosario opened 9 years ago

johndelrosario commented 9 years ago

Hi ryan, I absolutely love this plugin and currently using it in developing a library for components. However, I had to override to component binding handler in order to register the bindings i provide for the params attribute.

This is on the last part of init of the component handler

if (ko.bindingProvider.instance['registerBindings']) {
    ko.bindingProvider.instance.registerBindings(currentViewModel);
} else {
    throw new Error('Class binding provider must first be loaded to use custom component handler.');
}

ko.applyBindingsToDescendants(childBindingContext, element);

The way i declare the params for the binding class is like this

component: {
    params: {
        ///any
    }
}

I think it's kind of a bloat to overwrite the binding handler just to register the binding. Is there another way to extend the bindings without having to override? Thanks!

rniemeyer commented 9 years ago

@johndelrosario - one option for you, besides overwriting the binding, is to use an extensibility point around components that allows you to add your own component loader. For this scenario, we could add a loader that just implements a wrapper to the default loadViewModel function that tries to register bindings before creating a view model.

Perhaps something like:

ko.components.loaders.unshift({
    loadViewModel: function(name, config, callback) {
        var wrappedCallback = function(createViewModel) {
            // register binding before calling createViewModel
            var wrappedCreateViewModel = function(params) {
                if (params && params.bindings) {
                   ko.bindingProvider.instance.registerBindings(params.bindings);
                }

                // create the viewmodel, as it normally would be created
                return createViewModel.apply(this, arguments);
            };

            callback(wrappedCreateViewModel);
        }

        // call the original loadviewModel without wrapper to intercept
        ko.components.defaultLoader.loadViewModel(name, config, wrappedCallback);
    }
});

Here is a sample: http://jsfiddle.net/rniemeyer/Lq4zoLnc/

Does this work for your scenario? Possible that I could add something to this lib to help further.

akopchinskiy commented 5 years ago

@rniemeyer It's not working: https://codesandbox.io/s/zqqzk9ommx