简体   繁体   中英

jquery plugin development : prototype callback arguments

I've never really developed jquery plugins and I'm missing something with the concept... I'm trying to modify this image cropping plugin to have a new callback to set the aspect ratio dynamically.

So in cropper.js, I added a callback like this :

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 ...

}

And in my view :

var $cropper = $(".cropper");
//call the cropper
$cropper.cropper({ aspectRatio: 580 / 280 });
//change the ratio
$cropper.cropper("setAspectRatio",1600/585);

But the ratio is not passed to the callback. The console.log() outputs undefined.

What am I missing here?

To be able to pass arguments to the instance methods from the jQuery collection method, you will need to change the lines

        …
        if (typeof options === "string" && $.isFunction(data[options])) {
            data[options]();
        }
        …

in $.fn.cropper (at the very end of the file) to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM