Xavier
Xavier

Reputation: 399

How to apply a jquery plugin to a div which is generated by knockout template

was wondering if I can apply a jquery plugin to a div which is generated by knockout template.

Here is what I am doing: I have a template

<script type="text/html" id="single-file-image-template">
    <div id="iviewer"></div>
</script>

So how can I do something like what I did in jquery style?

  var iv = $('#iviewer').iviewer(
      'loadImage', documentUrl
  );

Any suggestions are welcome!

Regards
Xavier

Upvotes: 1

Views: 119

Answers (1)

Damien
Damien

Reputation: 8987

You can create a custom binding as follow :

ko.bindingHandlers.iviewer = {
   init: function (element, valueAccessor, allBindingsAccessor) {
     var value = ko.utils.unwrapObservable(valueAccessor());
       //initialize iviewer with url
      $(element).iviewer('loadImage', value);    
    },

     //update the control when the view model changes
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).iviewer('loadImage', value);
    }
};

And use it this this way :

<div data-bind="iviewer : url">
<div>

ko.applyBindings({ url : 'yourUrl'});

See fiddle

Upvotes: 2

Related Questions