Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 289
BAE Avatar asked Dec 10 '25 19:12

BAE


1 Answers

  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>
like image 125
Yurii Semeniuk Avatar answered Dec 12 '25 07:12

Yurii Semeniuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!