jQuery插件-在方法调用初始化期间使用选项

时间:2019-06-06 06:24:59

标签: jquery jquery-plugins

我正在使用this guide为自己创建一个插件,该插件可以创建并打开模式。我正在使用选项初始化覆盖默认值的插件。我也有一些要用于打开模式的方法。问题是,当我调用该方法时,我无权访问初始化期间使用的选项。我该如何处理?

$.fn.sheets = function(options){
    const sheets = this;
    let defaults = {
        type: 'standard'
    };

    const head = sheets.find('.head'),
        body = sheets.find('.body'),
        headHeight = head.outerHeight(),
        bodyHeight = body.outerHeight(),
        sheetHeight = headHeight+bodyHeight;

    if(options == 'open'){
        // opts is not defined here. extending the defaults will also not work. I need the information here if the sheet is of type standard or modal
        openSheet(sheets, head, body, opts);
    } else {
        const opts = $.extend({}, defaults, options);

        //code to initalize the plugin

        head.on('click', function(e){
            if(sheets.hasClass('active'))
                closeSheet(sheets, head, body);
            else
                openSheet(sheets, head, body, opts);
        });
    }

    function openSheet(sheets, head, body, opts){
        //code to open modal
    }

    function closeSheet(sheets, head, body){
        // code to close modal
    }
}

用法

//initializing with type modal
$('.sheets').sheets({
    type: 'modal'
});
$('.login-trigger').on('click', function(e){
    e.preventDefault();
    // open the modal
    $('.sheets').sheets('open');
});

0 个答案:

没有答案