0

我想创建一个同时具有方法和回调的 jQuery 插件,方法可以工作,但我无法让回调工作,回调的范围让我感到困惑,

(function($)
{
    var methods = {

        create: function(options) {

            var defaults = {
                width: 320,
                height: 240,
                background: '#000',
                onstop: function(){}
            };

            var options = $.extend(defaults, options);

            return $(this).each(function(i) {

                console.log('create');

            });

        },
        stop: function(options) {

            var defaults = {
                onstop: function(){}
            };

            var options = $.extend(defaults, options);

            return $(this).each(function(i) {

                console.log('stop');
                options.onstop.call();

            });
        }
    };

    $.fn.myplugin = function(option) {

        if (methods[option]) {
            return methods[option].apply( this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof option === 'object' || ! option) {
            return methods.create.apply(this, arguments);
        } else {
            $.error('Method ' +  option + ' does not exist in jQuery.plugin');
        }    
    };

})(jQuery);

所以在<script>

$(document).ready(function(){

    $('#start').click( function(){
        $('#myvideo').myplugin('create', { onstop: function(){ console.log('on stop'); } });
    });

    $('#stop').click( function(){
        $('#myvideo').myplugin('stop');
    });

});

基本上,我似乎想让 onstop: function(){} 对插件全局化

/* ======== 更新代码(见注释) ======== */

(function($)
{

    var callbacks = {
        onready: $.Callbacks("once memory unique").add(function() {
            //console.log('onready');
        }),
        ondeny: $.Callbacks("unique").add(function() {
            //console.log('ondeny');
        }),
        onerror: $.Callbacks("unique").add(function() {
            //console.log('onerror');
        }),
        onstop: $.Callbacks("unique").add(function() {
            //console.log('onstop');
        })
    };

    var methods = {

        construct: function(){
        },
        create: function(options) {

            var defaults = {
                width: 320,
                height: 240,
                background: '#000',
                onready: function(){},
                onstop: function(){}
            };

            var options = $.extend(defaults, options);

            return this.each(function(i, elements) {

                for (var prop in options) {
                    if (prop in callbacks) {
                        callbacks[prop].add(options.prop);
                    }
                }

                callbacks.onready.fire();

            });

        },
        stop: function() {

            return this.each(function(i, elements) {
                callbacks.onstop.fire();
            });
        }
    };

    $.fn.myplugin = function(option) {

        if (methods[option]) {
            return methods[option].apply( this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof option === 'object' || ! option) {
            return methods.construct.apply(this, arguments);
        } else {
            $.error('Method ' +  option + ' does not exist in jQuery.plugin');
        }    
    };

})(jQuery);
4

2 回答 2

1

我建议使用一些成熟的jQuery.Callbacks对象:

var callbacks = {
    onready: $.Callbacks("once memory unique").add(function() {
        console.log('ready');
    }),
    ondeny: $.Callbacks("unique").add(function() {
        console.log('deny');
    }),
    onerror: $.Callbacks("unique").add(function() {
        console.log('error');
    }),
    onstop: $.Callbacks("unique").add(function() {
        console.log('stop');
    })
};

现在,当你得到一些新的选择时,你可以做

for (var prop in options)
    if (prop in callbacks)
        callbacks[prop].add(options[prop]);

并调用它们只是做

callbacks.onstop.fire(/*args*/);

或者,如果您关心回调的上下文,请使用fireWith.

于 2012-11-21T18:33:37.837 回答
0

我使用 globalOptions 变量将插件初始化选项存储为全局,

这是用于测试和用作模板的两个文件。

jquery.plugin.js (函数($){

    var pluginName = 'myPlugin';

    var globalOptions = '';

    var methods = {

        create: function(options) {

            var defaults = {
                backgroundColor: '#000',
                color: '#fff',
                oncreate: function(){},
                onchangecolor: function(){},
                onloadpage: function(page){}
            };

            globalOptions = $.extend(defaults, options);

            return $(this).each(function(i, elements) {

                $(elements).data('globalOptions', globalOptions);

                globalOptions.oncreate();

            });

        },
        changeColor: function(){

            return $(this).each(function(i, elements) {

                globalOptions = $(elements).data('globalOptions');
                if (!globalOptions) { $.error('Error: ' + pluginName + ' has not been initialized yet'); return false; }

                $(this).css('background-color', globalOptions.backgroundColor);
                $(this).css('color', globalOptions.color);

                globalOptions.onchangecolor();

            });
        },
        loadPage: function(options){

            return $(this).each(function(i, elements) {

                globalOptions = $(elements).data('globalOptions');
                if (!globalOptions) { $.error('Error: ' + pluginName + ' has not been initialized yet'); return false; }

                globalOptions.onloadpage(options.page);
                location.href = options.page;

            });
        }

    };

    $.fn.myPlugin = function(option) {

        if (methods[option]) {
            return methods[option].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof option === 'object' || ! option) {
            return methods.create.apply(this, arguments);
        } else {
            $.error('Error: Method "' + option + '" does not exist in ' + pluginName);
            return false;
        }    
    };

})(jQuery); 

索引.html

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Example</title>
        <script src="jquery.min.js"></script>
        <script src="jquery.plugin.js"></script>
        <script>
$(document).ready(function() {

    var myElement = $('.container').myPlugin({
        color: '#555',
        backgroundColor: '#ddd',
        oncreate: function(){
            console.log('Callback: create');
        },
        onchangecolor: function(){
            console.log('Callback: onchangecolor');
        },
        onloadpage: function(page){
            console.log('Callback: onloadpage = '+page);
        }
    });

    $('.color').click(function(event){
        myElement.myPlugin('changeColor');
    });

    $('.page').click(function(event){
        myElement.myPlugin('loadPage', { page: '#test' });
    });

});
        </script>
    </head>
    <body>
        <div class="container">
            <button class="color">changeColor</button> <button class="page">loadPage</button>
        </div>
    </body>
</html>

如果有人有更好的方法和添加“私有”方法的方法,请分享。:)

于 2012-12-10T10:40:29.670 回答