javascriptsyntaxprotovis

Protovis - What are these functions with no curly braces?


Possible Duplicate:
Lambda function syntax in JavaScript without curly braces

Dealing with Protovis - they implement some strange delegate functions which are given without curly braces - can someone shade a light on it for me, please? Example:

vis.add(pv.Label)
.data(cols)
.left(function() this.index * w + w / 2)
.top(0)
.textAngle(-Math.PI / 2)
.textBaseline("middle");

Solution

  • In general, as explained in the question @missingno linked to, this is an alternate syntax for declaring functions, primarily supported by Firefox. Instead of:

    function() { return "stuff" };
    

    you omit the curly braces and return statement:

    function() "stuff";
    

    The end of the function occurs anywhere that a normal statement might end - a semicolon (;), a comma (,), or a close parenthesis ()).

    In Protovis, there are a lot of cases where you need to declare short, one-statement anonymous functions to pass in as arguments to method calls. This is such a common pattern that that library includes a parsing utility to make sure that the above syntax is supported in browsers other than Firefox. If you enclose your Protovis code in script tags like this:

    <script type="text/javascript+protovis">
    // ...
    </script>
    

    the script will be evaluated by the Protovis parser, which ensures support for the special syntax.

    My two cents on this: The upside of this syntax is that it's really fast (plus all the examples use it). A typically script using Protovis involves a lot of anonymous functions, so this can save you some typing, and it looks pretty awesome. When I first started using Protovis, I used it a lot - not just in method calls, but in variable declarations as well.

    But, it has a few really heavy problems:

    All that said, I still use it when I want to make a rough sketch quickly. But most of the time, I'd suggest sticking to normal script tags and standard, curly-braced function declarations.