Javascript jquery插件开发:原型回调参数
我从来没有真正开发过jquery插件,我缺少一些关于这个概念的东西。。。 我试图修改它,使其具有一个新的回调来动态设置纵横比 因此,在crapper.js中,我添加了如下回调:Javascript jquery插件开发:原型回调参数,javascript,jquery,plugins,callback,Javascript,Jquery,Plugins,Callback,我从来没有真正开发过jquery插件,我缺少一些关于这个概念的东西。。。 我试图修改它,使其具有一个新的回调来动态设置纵横比 因此,在crapper.js中,我添加了如下回调: Cropper.prototype = { construstor: Cropper, //init function with init code //My new function setAspectRatio: function(ratio) { console.
Cropper.prototype = {
construstor: Cropper,
//init function with init code
//My new function
setAspectRatio: function(ratio) {
console.log(ratio);
this.disable();
this.defaults.aspectRatio = ratio;
this.enable();
},
//more functions here ...
}
在我看来:
var $cropper = $(".cropper");
//call the cropper
$cropper.cropper({ aspectRatio: 580 / 280 });
//change the ratio
$cropper.cropper("setAspectRatio",1600/585);
但比率不会传递给回调。console.log()输出未定义
这里缺少什么?为了能够从jQuery集合方法向实例方法传递参数,您需要更改行
…
if (typeof options === "string" && $.isFunction(data[options])) {
data[options]();
}
…
在$.fn.crapper
中(在文件的最后)到
请向我们展示
$.fn.crapper
函数的定义,这是您正在调用的$crapper
函数,它应该转发“方法调用”。以下是完整的源代码(如果我在问题中复制太多代码,它将变得混乱):谢谢您的回答。它在某种程度上起作用,但是$croper.croper(“setAspectRatio”,1600/585);将HTMLImage元素传递给函数而不是我给出的比率,请您澄清一下…?哦,对了,它传递了每个
回调的参数。改编:-)谢谢你抽出时间,你真的帮助了我!我现在开始了解它的工作方式了
// Register as jQuery plugin
$.fn.cropper = function(options) {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var $this = $(this),
data = $this.data("cropper");
if (!data) {
data = new Cropper(this, options);
$this.data("cropper", data);
}
if (typeof options === "string" && $.isFunction(data[options])) {
data[options].apply(data, args);
}
});
};