2

I am trying to make a simple KO custom bindings wrapper for the "options" binding similar to what is described in this example. My goal is to have a custom binding that will apply select2.js to the specified select box.

I am trying to get started by just wrapping the options binding in a custom wrapper, but for some reason it is not working.

Here is what I have (jsFiddle) :

ko.bindingHandlers.select2 = {
  init: function (element) {
      ko.bindingHandlers.options.init(element);
  },
  update: function (element, valueAccessor, allBindingsAccessor) {
      ko.bindingHandlers.options.update(element, valueAccessor, allBindingsAccessor);
  }
};

Any help on this would be greatly appreciated.

JotaBe
  • 38,030
  • 8
  • 98
  • 117
Bradley Trager
  • 3,570
  • 3
  • 26
  • 33

1 Answers1

2

Looks like your issue is just related to the way that jsFiddle is loading the scripts. You had it set to onLoad, which was causing your applyBindings to be called prior to your creation of the custom binding.

If you change the fiddle to use something like No wrap in <body> it will work, except for one minor issue:

The options binding does not have an init binding in version 2.2 and below. It will have an init function in 2.3 and beyond. If you don't need to do anything further in your init function (strictly wrapping it), then you can do:

init: ko.bindingHandlers.options.init,
update: function (element, valueAccessor, allBindingsAccessor) {
   ko.bindingHandlers.options.update(element, valueAccessor, allBindingsAccessor);
}

It will either be undefined or use what is there (for 2.3+).

Sample: http://jsfiddle.net/rniemeyer/AerJ5/

RP Niemeyer
  • 114,592
  • 18
  • 291
  • 211
  • I am just wondering how to find out if a binding has a init/update function and what the parameters are. When I looked on GitHub at the options binding (https://github.com/SteveSanderson/knockout/blob/master/src/binding/defaultBindings/options.js) it seemed to have an init function that checked to make sure the element was a select input and then removed any options that were there. – Bradley Trager May 06 '13 at 15:43
  • 1
    @BinyominTrager - it is a little confusing in this case. We did update the `options` binding in code that is unreleased (will be in 2.3). This is a very rare thing (add/remove an init/update method on a core binding). You would have to check if it exists before calling it, if you want to support old/new versions of KO. I will update the answer to demonstrate. – RP Niemeyer May 06 '13 at 15:50
  • Thank you again, definitely good to know. For the future I think the easiest way would be to just use the console to inspect the binding handler that I am trying to wrap. – Bradley Trager May 06 '13 at 16:12
  • @BinyominTrager - true, but in this case if you want to be able to support multiple versions of KO (maybe not relevant in your case), then you might want to take it into consideration. – RP Niemeyer May 06 '13 at 16:32