RequireJS: How to load multiple functions from one module?
javascript, requirejs
Solution
As far as RequireJS is concerned you have four modules there, and they are all in one file. (As many modules as `define` calls.) The basic rules for proper operation of RequireJS are that you should have one module per file and your `define` calls should not name their modules. (The optimizer `r.js` adds module names.) There are some exceptions to these rules but you really need to know what you are doing to use these exceptions (and be able to explain why you need to do something different than the basic rule).
What you can do is to have your `tmp/assets/scripts/admin/modules/caplet.color.js` file contain one module that exports all the functions you need:
define(function() {
function inColor() {...}
function fillColor() {...}
function rgbaColor() {...}
return {
inColor: inColor,
fillColor: fillColor,
rgbaColor: rgbaColor
};
});
Problem
I have a module that needs to return 3 functions,i wrote the module like this (sorry about all the `return`s, I translated this directly from coffeescript): ``` (function() { define("inColor", [], function() { var init; init = function(value, obj) { var foundVal; foundVal = void 0; $.each(obj, function(key, val) { if (value === key) { foundVal = val; } }); return foundVal; }; return init; }); define("fillColor", ['inColor'], function(inColor) { var capletColor, init; capletColor = { primary: "#3DA0DB", info: "#B5D1D8", success: "#2ECC71", warning: "#FFCC33", danger: "#E15258", inverse: "#62707D", theme: "#f37864", "theme-inverse": "#6CC3A0", palevioletred: "#913B53", green: "#99CC00", lightseagreen: "#1ABC9B" }; init = function(obj) { var codeColor; inColor = inColor(obj.data("color") || obj.data("toolscolor"), capletColor); codeColor = inColor || obj.data("color") || obj.data("toolscolor"); return codeColor; }; return init; }); define("rgbaColor", [], function() { var init; init = function(hex, opacity) { var b, bigint, g, r; bigint = parseInt(hex.replace("#", ""), 16); r = (bigint >> 16) & 255; g = (bigint >> 8) & 255; b = bigint & 255; if (opacity || opacity <= 1) { return "rgba(" + r + "," + g + "," + b + "," + (opacity || 1) + ")"; } else { return "rgb(" + r + "," + g + "," + b + ")"; } }; return init; }); define('colorModuleLoader', ['inColor', 'fillColor', 'rgbaColor'], function(inColor, fillColor, rgbaColor) { return { inColor: inColor, fillColor: fillColor, rgbaColor: rgbaColor }; }); }).call(this); ``` Now i load my module like this: ``` require(['tmp/assets/scripts/admin/modules/caplet.color'], function(colorModuleLoader) { return window.alert(colorModuleLoader.rgbaColor("#F37864", 0.1)); }); ``` The module is loaded, but error says `colorModuleLoader` is `undefined` when i try t alert the value,can anyone explain why?