var Gallery = Backbone.Controller.extend({ _index: null, _photos: null, _album :null, _subalbums:null, _subphotos:null, _data:null, _photosview:null, _currentsub:null, routes: { "": "index", "subalbum/:id": "subindex", "subalbum/:id/" : "directphoto", "subalbum/:id/:num" : "hashphoto" }, initialize: function(options) { var ws = this; if (this._index === null){ $.ajax({ url: 'data/album1.json', dataType: 'json', data: {}, success: function(data) { ws._data = data; ws._photos = new PhotoCollection(data); ws._index = new IndexView({model: ws._photos}); Backbone.history.loadUrl(); } }); return this; } return this; }, //Handle rendering the initial view for the //application index: function() { this._index.render(); },
I'm reading a tutorial on backbone.js here: http://addyosmani.com/blog/building-spas-jquerys-best-friends/
What are the underscores? (_index, _photos, _album) Why use them?
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object. Alone, this refers to the global object.
The Underscore. js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _. first() function is used to return the first element of the array, i.e. the number at the zeroth index.
The _.each function accepts an array or an object, an iteratee function and an optional context object, the iteratee function is invoked once and in order for each array item The iteratee function provides 3 arguments item - The current iterated object (or value if an object was passed) i - The index of the iterated ...
Double underscore (__) in front of a variable is a convention. It is used for global variable (The following variables may appear to be global but are not, rather local to each module) in Nodejs meanwhile Underscore(_) used to define private variable.
It means private fields or private methods. Methods that are only for internal use.
They should not be invoked outside of the class.
Private fields contain data for internal use.
They should not be read or written into (directly) from outside of the class.
Note: It is very important to note that just adding an underscore to a variable does not make it private, it is only a naming convention.
As far as I'm aware, it's generally used to indicate a private variable (but doesn't actually provide any privacy, just a convention).
It's discussed briefly here, though they're advised against: http://javascript.crockford.com/code.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With