2

I got stuck in something and I know it might be silly! I try to figure out what the parenthesis ")()" at the end of this code do? jsFiddle Since if I remove them it does not show any thing. I need to add more function in this part of the code but because of the parenthesis I got the errors.

(function () {

    var n = 143,
        duration = 750,
        now = new Date(Date.now() - duration),
        count = 0,
        data = d3.range(n).map(function () {
            return 0;
        });

    var margin = {
        top: 6,
        right: 0,
        bottom: 20,
        left: 40
    },
    width = 560 - margin.right,
        height = 120 - margin.top - margin.bottom;

    var x = d3.time.scale()
        .domain([now - (n - 2) * duration, now - duration])
        .range([0, width]);

    var y = d3.scale.linear()
        .range([height, 0]);

    var line = d3.svg.line()
        .interpolate("basis")
        .x(function (d, i) {
        return x(now - (n - 1 - i) * duration);
    })
        .y(function (d, i) {
        return y(d);
    });

    var svg = d3.select("body").append("p").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .style("margin-left", -margin.left + "px")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.append("defs").append("clipPath")
        .attr("id", "clip")
        .append("rect")
        .attr("width", width)
        .attr("height", height);

    var axis = svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(x.axis = d3.svg.axis().scale(x).orient("bottom"));

    var path = svg.append("g")
        .attr("clip-path", "url(#clip)")
        .append("path")
        .data([data])
        .attr("class", "line");

    tick();

    d3.select(window)
        .on("scroll", function () {
        ++count;
    });

    function tick() {

        // update the domains
        now = new Date();
        x.domain([now - (n - 2) * duration, now - duration]);
        y.domain([0, d3.max(data)]);

        // push the accumulated count onto the back, and reset the count
        data.push(Math.random()*10);
        count = 0;

        // redraw the line
        svg.select(".line")
            .attr("d", line)
            .attr("transform", null);

        // slide the x-axis left
        axis.transition()
            .duration(duration)
            .ease("linear")
            .call(x.axis);

        // slide the line left
        path.transition()
            .duration(duration)
            .ease("linear")
            .attr("transform", "translate(" + x(now - (n - 1) * duration) + ")")
            .each("end", tick);

        // pop the old data point off the front
        data.shift();

    }
})()

Thank you!!

Yotam Omer
  • 15,310
  • 11
  • 62
  • 65
star
  • 317
  • 2
  • 6
  • 15

3 Answers3

1

Immediately-Invoked Function Expression (IIFE)

Good reading here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

You can of course add into it any functions but because of scoping, you can call these functions only in same or deeper scope.

e.g test() function: http://jsfiddle.net/ZaJZu/

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • Suppose I want to add something like: d3.tsv("data/dataMulti.tsv", function(error, data) { color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; })); instead of test(); I still get the errors as soon as I write a function!! – star Jun 29 '13 at 12:43
1

You defined an anonymous functions. Usually a named function like:

function myfunc(){
   //code
}

can be called:

myfunc();

Exactly this () parenthesis are doing.It called the anonymous function on completion. If you don't want these, then named your function and call it from where you need as give example above.

Updated fiddle without Parenthesis

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • I named myfunction myfunc() and called it instead of using this anonymous unction but when I add another function I still see the error "Uncaught SyntaxError: Unexpected end of input ". I added the new function after myfunc()!! – star Jun 29 '13 at 12:20
  • ask another question with that code including that new function – Zaheer Ahmed Jun 29 '13 at 12:21
0

The outer parentheses around the whole thing turn the function into a function expression (as opposed to a function declaration). There are other ways to do that, but the parentheses are the common convention. The () at the end of the function expression is what triggers the immediate function invocation.

This is not a self-invoked anonymous function as that would be a recursive function. The pattern is called an Immediately-Invoked Function Expression (IIFE). It’s commonly used in the module pattern, but it’s also used relatively often to assign the result of a small, inline function to a variable. Regular old invoked-later function expressions (without the () at the end) are also commonly passed as callbacks or assigned to variables, or used inline in object literals to define methods.

Peter Richmond
  • 396
  • 5
  • 6