4

I am currently trying to optimize the current jQuery (development version 1.8.1) with r.js. This happens during asset compilation in a rails project with the gem requirejs-rails.

I think I encountered a bug in the optimizer. Around line 999 in the jquery source, you will find the following code:

(function add(args) {
    jQuery.each(args, function (_, arg) {
        var type = jQuery.type(arg);
        if (type === "function" && (!options.unique || !self.has(arg))) {
            list.push(arg);
        } else if (arg && arg.length && type !== "string") {
            // Inspect recursively
            add(arg);
        }
    });
})(arguments);

When the optimized jquery gets to the line containing add(arg); an error will be thrown, that add is not defined. This is, because the optimizer renamed the function add to e, while the function call remained add(...)like so:

(function e(args) {
    jQuery.each(args, function (_, arg) {
        var type = jQuery.type(arg);
        if (type === "function" && (!options.unique || !self.has(arg))) {
            list.push(arg);
        } else if (arg && arg.length && type !== "string") {
            // Inspect recursively
            add(arg);
        }
    });
})(arguments);

I was able to fix the code, by rewriting it to:

var fnAdd = function (args) {
    jQuery.each(args, function (_, arg) {
        var type = jQuery.type(arg);
        if (type === "function" && (!options.unique || !self.has(arg))) {
            list.push(arg);
        } else if (arg && arg.length && type !== "string") {
            // Inspect recursively
            console.log("inspecting", fnAdd);
            fnAdd(arg);
        }
    });
};
fnAdd(arguments);

Can this be considered a bug in r.js? Or is it not allowed javascript? I wonder why I am the first one having the problem (at least google didnt reveil any solutions).

matt b
  • 138,234
  • 66
  • 282
  • 345
Erik
  • 11,944
  • 18
  • 87
  • 126

1 Answers1

1

My guess would be it looks like a bug to me. Whilst I wouldn't personally use the syntax you are using, it is valid JavaScript so to me It looks like r.js isn't designed to handle recursive function calls of this type.

Out of interest what happens if you put an add() call outside of itself? Does r.js rename it correctly to e()?

Pebbl
  • 34,937
  • 6
  • 62
  • 64