如何将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);
});
当然不行。有什么想法吗?
答案 0 :(得分:3)
这是example,可以使用或不使用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的引用。 glue函数检测是否存在AMD环境(RequireJS是)。如果是这样,它需要jquery
模块并将其作为jQuery引用传递。如果没有,它的行为与非AMD感知插件的行为方式相同。