Knockout.js - cannot wrap 'c', 'foreach' and other template bindings

I am trying to create a custom binding that wraps an existing binding, namely the "c" or "foreach" bindings built into the knockout.

Unfortunately, I get the following error when doing this: Uncaught TypeError: Cannot call method 'createChildContext' of undefined from knockout-latest.debug.js: 3060 (the problem also appears on version 2.1.0).

I reproduced the exception in jsFiddle , with Google Chrome 21.0.1180.57.

User binding is simply defined as follows:

 ko.bindingHandlers.myWith = { init: function(element, valueAccessor, allBindings, viewModel) { // do things return ko.bindingHandlers.with.init(element, valueAccessor, allBindings, viewModel); }, update: function(element, valueAccessor, allBindings, viewModel) { return ko.bindingHandlers.with.update(element, valueAccessor, allBindings, viewModel); } }; 

One could โ€œwrapโ€ existing bindings with a simple handler in the form above, much as discussed in this article .

+4
source share
1 answer

In KO 2.0, binding handlers actually take the 5th argument, which is the binding context. The binding context contains things like $data , $parent , $parents , $root .

So, you just need to forward this parameter to:

 ko.bindingHandlers.myWith = { init: function(element, valueAccessor, allBindings, viewModel, context) { // do things return ko.bindingHandlers.with.init(element, valueAccessor, allBindings, viewModel, context); }, update: function(element, valueAccessor, allBindings, viewModel, context) { return ko.bindingHandlers.with.update(element, valueAccessor, allBindings, viewModel, context); } }; 

http://jsfiddle.net/rniemeyer/48uJg/2/

or

 ko.bindingHandlers.myWith = { init: function() { return ko.bindingHandlers.with.init.apply(this, arguments); }, update: function() { return ko.bindingHandlers.with.update.apply(this, arguments); } }; 
+12
source