我正在尝试转换所有可以在有或没有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);
但是我怎么能调用第一个插件样板,因为我不再在这个样板中存储插件名手动?
答案 0 :(得分:1)