Я пытаюсь преобразовать весь мой jquery-плагин, который может работать с или без среды AMD.
плита,
Бойлер 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 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();
});
Так я бы назвал плагин ранее для такого типа шаблонов,
Бойлер 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);
Но как я могу назвать первый плагин шаблонным как я не храню имя плагина вручную больше внутри этого шаблонного?
Я использую следующий шаблон для плагинов jQuery с поддержкой AMD
https://gist.github.com/simonsmith/4353587
Вам все равно нужно предоставить плагину имя, иначе не было бы способа предоставить его прототипу jQuery.