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

时间:2014-04-19 12:01:46

标签: javascript jquery plugins callback

我从来没有真正开发过jquery插件,而且我对这个概念遗漏了一些东西...... 我尝试修改此image cropping plugin以使用新的回调来动态设置宽高比。

所以在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()输出undefined。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

为了能够从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);
        }
    });
};
相关问题