The other day I was creating my first Knockout Custom Binding which was pretty straight forward. But I was a bit stumped as to what was the ‘best’ practice for where to put this custom binding. Of course I did not want to put it in my view model as that would defeat the purpose/idea behind creating a custom binding, which is to provide a global, reusable way to perform an action. My gut told me to put the binding in its own file but I thought I would ask twitter for its advice and below are some of the responses I received, this told me I was on the right path.
Since the conclusion was to put all custom Knockout bindings in their own file the only thing left to do was to implement this. Here is what I did.
Create CustomKnockoutBindings.ts file
In my case I am using Typescript (in case .ts extension threw you off) So I needed to implement the code below:
If you look at the implemented code you should understand 2 things
- We are going to create our bindings within the jQuery Document Ready method. This will allow for our bindings to be created when the page loads. This also prevents us from having to ‘call an init’ method from any of our view models
- We are extending the KnockoutBindingHandlers interface (this is found in knockout.d.ts). We need to extend this interface otherwise you will get a compile error from Typescript saying that bindingHandlers.strikeThroughCompleted does not exist on KnockoutBindingHandlers
Once you have the above implemented you should be good to go, only thing left to do now is to implement this in side your HTML.
Implement my custom binding in HTML
In the code above you can see that I am using our strikeThroughCompleted binding in the same manor as the ‘text’ binding immediately to its left.
Till next time,
03-17-2013 6:10 AM