如何将jquery样板转换为require样板?

如何将jquery命名空间插件转换或放入require样板? 对于国际事务,

这通常是我标准的jquery样板,

// A namepace structure: (function($){ // Initial setting. var pluginName = 'BR_account'; var storageName = 'plugin_' + pluginName; var methods = { init : function( options ) { console.log("this is a jquery plugin boilerplate in requirejs boilerplate"); // nothing returned. } }; $.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); 

这通常是需要样板,

 //Filename: boilerplate.js define([ // These are path alias that we configured in our bootstrap 'jquery', // lib/jquery/jquery 'underscore', // lib/underscore/underscore 'backbone' // lib/backbone/backbone ], function($, _, Backbone){ // Above we have passed in jQuery, Underscore and Backbone // They will not be accessible in the global scope return {}; // What we return here will be used by other modules }); 

但是我怎么能把它们混合在一起 – 或许我不应该?

这是我的考验,

 define([ 'jquery', 'underscore', 'backbone' ], function($, _, Backbone){ console.log(Backbone); // I get an object of Backbone // A namepace structure: (function($){ // Initial setting. var pluginName = 'BR_account'; var storageName = 'plugin_' + pluginName; var methods = { init : function( options ) { console.log("this is a jquery plugin boilerplate in requirejs boilerplate"); // nothing returned. } }; $.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); }); 

它当然不起作用。 有任何想法吗?

这是一个有或没有RequireJS的例子 :

 (function (factory) { // If in an AMD environment, define() our module, else use the // jQuery global. 'use strict'; if (typeof define === 'function' && define.amd) define(['jquery'], factory); else factory(jQuery); }(function ($) { 'use strict'; // This is the plugin proper. $.fn.findAndSelf = function(selector) { var $nodes = this.find(selector); if (this.is(selector)) $nodes = $nodes.add(this); return $nodes; }; })); 

它的工作方式是使用工厂函数作为唯一参数调用glue函数(代码中的第一个函数)。 工厂函数只需要获取对jQuery的引用。 粘合function检测是否存在AMD环境(RequireJS)。 如果是这样,它需要jquery模块并将其作为jQuery引用传递。 如果没有,它的行为方式与非AMD感知插件的行为方式相同。