user3019830
user3019830

Reputation: 11

Backbone namespacing

I'm trying to learn backbone from the book "Developing Backbone.js applications".
It describes the infamous TodoMVC app, which I also checked out in several online tutorials.

I can't seem to find anywhere an explanation about the meaning of this line of code :

var app = app || {} ;

In the book, the code for models, views, collections, routers is split in separate files that are placed in corresponding folders. Each file starts with this code but there is no explanation about why it starts with this. I assume it's some kind of namespacing, and || is the logical Or operator, but frankly I have no idea what they're trying to accomplish here.

Anybody who can enlighten me?
Valleyken

Upvotes: 1

Views: 95

Answers (3)

David Morrow
David Morrow

Reputation: 9354

window.app = app || {};
app.models = app.models || {};
app.models.myModel = {
  myfunction: function () {
    // your code...
  }
}

this allows you to create empty objects that you will store all your Javascript objects in. (namespacing) keeping your objects organized and not on the window (global namespace)

the || {} simply keeps you from accidentally setting your namespace to an empty objects should the load order of your javascript files change. It checks to make sure there is not already an object there before setting it to {}

Upvotes: 0

nikoshr
nikoshr

Reputation: 33364

At some point in building your app, you probably will want to load your files asynchronously, which implies that you won't control in what order the files are interpreted and thus when your app variable is declared.

Using var app = app || {} ; lets you use a variant on the Loose Augmentation pattern : you can roughly translate this statement to If app is already declared, keep it, if not create a new object and use it.

And see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators for the explanation of the inner workings of this statement :

The && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

Upvotes: 1

homtg
homtg

Reputation: 1999

Usually this is done to set a default value to your local variable if it is not passed:

function(arg){
 var arg = arg || {};
 console.log(arg);
}

If arg is passed you will set the local variable arg to the passed object, otherwise you will create a new object by {} and set the local arg variable to this object.

See: Function required and not-required variables

Upvotes: 0

Related Questions