【问题标题】:Change settings of custom jquery plugin using Knockout使用 Knockout 更改自定义 jquery 插件的设置
【发布时间】:2015-09-23 17:31:32
【问题描述】:

我创建了一个非常基本的 jquery 插件。只需更改 div 的 with 即可。现在,我想使用 knockoutjs 动态更新该插件的设置。我似乎无法理解如何做到这一点,甚至不知道从哪里开始。这就是我到目前为止所拥有的。

<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"));

【问题讨论】:

  • 在淘汰赛中最好的方法是为那个 jQuery 插件写一个binding handler。我觉得从头开始这样做对于 Stack Overflow 的回答来说有点宽泛,但是如果需要的话,一定要看看编写一个处理程序并询问有关该方法的更具体的问题。

标签: javascript jquery knockout.js


【解决方案1】:

您可以做的最简单的事情是订阅变量:

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

但是,您违反了淘汰赛的基本规则,即“不要在绑定处理程序之外与 DOM 混为一谈。”

您的插件的custom binding handler 看起来像这样:

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()
    });
  }
};

你会绑定类似的东西

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

你的视图模型有一个配置变量,比如

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

最后,如果您不打算在没有 Knockout 的情况下使用该插件,则不需要 jQuery 插件。您可以将所有代码编写为自定义绑定处理程序的一部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多