AMD插件样板:如何在非AMD环境下执行插件?

时间:2013-12-04 14:03:01

标签: jquery backbone.js requirejs amd js-amd

我正在尝试转换所有可以在有或没有AMD环境的情况下工作的jquery插件。

样板,

Boilerplate 1:

(function (factory) {

    // If in an AMD environment, define() our module, else use the jQuery global.
    if (typeof define === 'function' && define.amd)
        define(['jquery'], factory);
    else
        factory(jQuery);

}(function ($) {

    var apple = $.fn.extend({
        defaults: {
            element:            '',
            onSuccess: function() {}
        },
        getInfo: function (options) {

            // Confirm a varible for the plugin's root itself.
            var base = this; 

            // Process the setting.
            var properties = $.extend(true, {}, this.defaults, options );
            return properties;
        }
    });

    return apple;

}));

这在AMD环境中工作正常。它可以和requirejs一起使用(我猜也是使用backbone.js),

require.config({
    paths: {
        jquery: 'ext/jquery/jquery-min',
        underscore: 'ext/underscore/underscore-min',
        backbone: 'ext/backbone/backbone-min',
        text: 'ext/text/text'
    },
    shim: {
        jquery: {
            exports: '$'
        },
        underscore: {
            deps:['jquery'],
            exports: '_'
        },
        backbone: {
            deps:['jquery','underscore','text'],
            exports: 'Backbone'
        }
     }
});

require([
    // Load our app module and pass it to our definition function
     'app/plugin'

], function(Plugin){

    Plugin.getInfo({
        text:"hello world",
        element:"#target",
        onSuccess:function(){
            console.log("callback");
        }
    });

});

但是如何在jquery标准方法中执行此插件?如下所示,

$(document).ready(function(){
    $.fn.myPluginName(); 
});

这就是我之前为这种样板文件调用插件的方法,

Boilerplate 2:

     // This is the plugin.
    (function($){

        // Initial setting.
        var pluginName = 'myPluginName';
        var storageName = 'plugin_' + pluginName;

        var methods = {

            init : function( options ) {
                return options;
            }
        };

        $.fn[pluginName] = function( method ) {

            if ( methods[method] ) {
                return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
            } else if ( typeof method === 'object' || ! method ) {
                return methods.init.apply( this, arguments );  // always change 'init' to something else if you different method name.
            } else {
                $.error( 'Method ' +  method + ' does not exist on jQuery.' + pluginName + '.' );
            }
            return this; 
        };

        $.fn[pluginName].defaults = {
            onSuccess: function() {}
        };

    })(jQuery);

但是我怎么能调用第一个插件样板,因为我不再在这个样板中存储插件名手动

1 个答案:

答案 0 :(得分:1)

我将以下模板用于支持AMD的jQuery插件

https://gist.github.com/simonsmith/4353587

你仍然需要为插件命名,否则将无法将其暴露给jQuery原型。