Search code examples
javascriptjquerybackbone.jsiife

What are these patterns in this Backbone TodoMVC example


Looking into the todomvc backbone codes example. The structure in the js/ fold:

├── app.js
├── collections
│   └── todos.js
├── models
│   └── todo.js
├── routers
│   └── router.js
└── views
    ├── app-view.js
    └── todo-view.js

app.js

var app = app || {};
$(function () {
    'use strict';
    // kick things off by creating the `App`
    new app.AppView();
});

collections/todos.js

var app = app || {};

(function () {
    'use strict';
    var Todos = Backbone.Collection.extend({
    model: app.Todo,
    app.todos = new Todos();
})();

models/todo.js

var app = app || {};

(function () {
    'use strict';
    app.Todo = Backbone.Model.extend({
    });
})();

views/app-view.js

var app = app || {};
(function ($) {
    'use strict';
    app.AppView = Backbone.View.extend({
})(jQuery);

I have two questions:

  1. why var app = app || {} in each file?

  2. What are the differences between $(function(){}), (function(){})(), and (function($))(jQuery)?


Solution

    1. app variable is global and encapsulates entire Backbone application to minimize global namespace pollution. Here you can find more details about Namespacing Patterns.

      var app = app || {} initializes global app variable with new empty object if it is not initialized yet. Otherwise it will be untouched.

    2. The functions:

      • $(function(){}) is a shortcut for jQuery's $(document).ready(function(){}). Docs
      • (function(){})() is an Immediately-invoked function expression (IIFE) without parameters
      • (function($){ /* here $ is safe jQuery object */ })(jQuery) is IIFE with parameter - jQuery object will be passed as $ into that anonymous function

    $(function() {
      console.log("Document ready event");
    });
    
    $(document).ready(function() {
      console.log("Document ready event");
    });
    
    (function() {
      console.log("Immediately-invoked function expression without parameters");
    })();
    
    (function($) {
      console.log("Immediately-invoked function expression with parameter. $ is a jQuery object here:");
      console.log($.fn.jquery);
    })(jQuery);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>