jquery插件开发:原型回调参数

jquery plugin development : prototype callback arguments

本文关键字:回调 参数 原型 插件 开发 jquery      更新时间:2023-09-26

我从来没有真正开发过jquery插件,我在这个概念上有所欠缺。。。我正在尝试修改这个图像裁剪插件,以便有一个新的回调来动态设置纵横比。

因此,在cropper.js中,我添加了一个回调:

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.cropper中(在文件的最后)到

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