2

I create a very basic jquery plugin. Simply changing the with of the div. Now, I want to use knockoutjs to dynamically update the settings of that plugin. I cant seem to get my head around how to do this or even where to start. This is what I have so far.

<div class="mychart"></div>
  <input type="text" data-bind="value: chartwidth"/>
  <input type="text" data-bind="value: chartheight"/>
    <script src="jquery.js"></script>
  <script src="knockout.js"></script>
  <script src="chartjs.js"></script>
  <script>

    $(".mychart").nbchart({
      width:'200px',
      height:'200px'
    });

    // Here's my data model
    var ViewModel = function(cwidth,cheight) {
        this.chartwidth = ko.observable(cwidth);
        this.chartheight= ko.observable(cheight);
    };

    ko.applyBindings(new ViewModel("100px","100px"));
Nat Ritmeyer
  • 5,634
  • 8
  • 45
  • 58
EugeneDeWaal
  • 216
  • 2
  • 15
  • Chances are the best way to do this in knockout would be to write a [binding handler](http://knockoutjs.com/documentation/custom-bindings.html) for that jQuery plugin. I feel doing so from scratch is a bit broad for a Stack Overflow answer though, but by all means take a look at writing a handler and asking more specific questions about that approach if you need to. – James Thorpe Aug 13 '15 at 12:21

1 Answers1

2

The easiest thing you could do is subscribe to the variables:

this.chartwidth.subscribe(function (newValue) {
  $(".mychart").nbchart({width:newValue});
});

However, you are violating the Cardinal Rule of Knockout, which is "Don't mess with the DOM outside of a binding handler."

A custom binding handler for your plugin would look something like this:

ko.bindingHandlers.nbchart = {
  init: function (element, valueAccessor) {
    $(element).nbchart();
  },
  update: function (element, valueAccessor) {
    var config = ko.unwrapObservable(valueAccessor());
    $(element).nbchart({
      width: config.width(),
      height: config.height()
    });
  }
};

and you would bind something like

<div data-bind="nbchart:config"></div>

where your viewmodel has a config variable like

var ViewModel = function(cwidth,cheight) {
    this.chartwidth = ko.observable(cwidth);
    this.chartheight= ko.observable(cheight);
    config: {
      width: this.chartwidth,
      height: this.chartheight
    }
};

Finally, if you are not planning to use the plugin without Knockout, you don't need a jQuery plugin. You can just write all the code as part of your custom binding handler.

Roy J
  • 42,522
  • 10
  • 78
  • 102