Feb 09, 2017

KnockoutJS/Jquery Tip: Custom Bindings

I faced the following problem today: How can I initialize jQuery components after being loaded by KnockoutJS? Specifically I was trying to initialize a select2 component.

The first naive solution was to try using something like:

<script type="text/javascript">
  $(document).ready(function() {

That did not work.

After a quick googling I found this Stackoverflow question, How to use jQuery in a Knockout.js Template?; sadly for whatever reason none of the current answers are marked as a solution although is clear the one with the most upvotes answers it correctly: you have to use custom bindings.

I created a jsFiddle demonstrating this solution, really cool stuff: