gpt4 book ai didi

javascript - 使用 Knockout 更改自定义 jquery 插件的设置

转载 作者:行者123 更新时间:2023-11-29 21:43:16 26 4
gpt4 key购买 nike

我创建了一个非常基本的 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"));

最佳答案

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

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

但是,您违反了 Knockout 的基本规则,即“不要在绑定(bind)处理程序之外弄乱 DOM”。

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

然后你会绑定(bind)类似的东西

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

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

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

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

关于javascript - 使用 Knockout 更改自定义 jquery 插件的设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31988029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com