使用Knockout更改自定义jquery插件的设置 [英] Change settings of custom jquery plugin using Knockout
问题描述
我创建了一个非常基本的jquery插件。只需更改div的内容即可。现在,我想使用knockoutjs动态更新该插件的设置。我似乎无法理解如何做到这一点,甚至从哪里开始。这就是我到目前为止所拥有的。
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"));
推荐答案
你能做的最简单的事情就是订阅变量:
The easiest thing you could do is subscribe to the variables:
this.chartwidth.subscribe(function (newValue) {
$(".mychart").nbchart({width:newValue});
});
但是,你违反了Knockout的基本规则,即不要乱用DOM在绑定处理程序之外。
However, you are violating the Cardinal Rule of Knockout, which is "Don't mess with the DOM outside of a binding handler."
A 自定义绑定处理程序如下所示:
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>
你的viewmodel有一个配置变量,如
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
}
};
最后,如果您不打算在没有Knockout的情况下使用该插件,则不需要jQuery插入。您可以将所有代码编写为自定义绑定处理程序的一部分。
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.
这篇关于使用Knockout更改自定义jquery插件的设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!