Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good reason for wrapping an extra immedeately-invoked function around a requireJS module definition?

I was looking at the Backbone-requireJS boilerplates in GitHub, I see two different types of implementations.

https://github.com/david0178418/BackboneJS-AMD-Boilerplate/blob/master/src/js/views/viewStub.js has the following as the viewStub:

function() {
    "use strict";

    define([
            'jqueryLoader',
            'underscore',
            'backbone',
        ],
        function($, _, Backbone) {

            return Backbone.View.extend({
                template : _.template(/*loaded template*/),

                initialize : function() {
                    this.render();
                },

                render : function() {
                    $(this.el).append(this.template(/*model/collection*/));

                    return this;
                }
            });
        }
    );
})();

Whereas the view-stub from the other boilerplate https://github.com/jcreamer898/RequireJS-Backbone-Starter/blob/master/js/views/view.js has the following:

define([
        'jquery', 
        'backbone',
        'underscore', 
        'models/model',
        'text!templates/main.html'], 
function($, Backbone, _, model, template){
    var View = Backbone.View.extend({
        el: '#main',
        initialize: function(){
            this.model = new model({
                message: 'Hello World'
            });
            this.template = _.template( template, { model: this.model.toJSON() } );
        },
        render: function(){
            $(this.el).append( this.template );
        }
    });

    return new View();
}); 

My question here is: Why is there a self-executing function around the whole RequireJS module in the first example?

like image 565
Karthik Avatar asked Nov 14 '22 12:11

Karthik


1 Answers

There doesn't need to be a containing closure in this example. It creates a scope so that declared variables or functions don't leak into the global scope. But when you are not creating variables or named functions, then there is nothing to leak. So there isn't much point.

The real reason may be simpler than you think. Like using the turn signal even if noone is around, enclosing every JS source file in a self executing function is a good habit to get into. It saves you from stupid mistakes. So it may just be an example of a defensive programming style.

There is no benefit in this example, but the related performance cost at runtime is totally negligible. So why not do it the "right" way in case some one new comes in and "maintains" this module in some funky ways?

like image 111
Alex Wayne Avatar answered Nov 16 '22 03:11

Alex Wayne