Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat does the underscore marking do in backbone and when do we use it?
    text
    copied!<p>I'm going through the process of learning backbone and don't understand all of the syntax. Below I put in some of the code I've been working through to learn backbone so I could reference it in this question. While I get most of how backbone works, I don't quite understand some of the meanings behind a few of the markings in some of the code. The source of documentation of BackBone is scarce at best. I get 90% of it however the syntax I don't get is what does the underscore '_' really provide and when to use it. For instance below there is code that uses the underscore at the ".bindAll( .... " Of course I do understand what the binding is. Just not sure of when to use the underscore and what role the marking plays. Another example is when the underscore shows itself before the '(this.collection.models).each(function(item)...' code below. I get that the code is doing a loop however why are they using underscore marking. Thanks for your help.</p> <pre><code>(function($){ var Item = Backbone.Model.extend({ defaults: { part1: 'hello', part2: 'world' } }); var List = Backbone.Collection.extend({ model: Item }); var ListView = Backbone.View.extend({ el: $('body'), events: { 'click button#add': 'addItem' }, initialize: function(){ _.bindAll(this, 'render', 'addItem', 'appendItem'); // remember: every function that uses 'this' as the current object should be in here this.collection = new List(); this.collection.bind('add', this.appendItem); // collection event binder this.counter = 0; //once the object is initialized, render the page. this.render(); }, render: function(){ var self = this; $(this.el).append("&lt;button id='add'&gt;Add list item&lt;/button&gt;"); $(this.el).append("&lt;ul&gt;&lt;/ul&gt;"); _(this.collection.models).each(function(item){ // in case collection is not empty self.appendItem(item); }, this); }, addItem: function(){ this.counter++; var item = new Item(); item.set({ part2: item.get('part2') + this.counter // modify item defaults }); this.collection.add(item); // add item to collection; view is updated via event 'add' }, appendItem: function(item){ $('ul', this.el).append("&lt;li&gt;"+item.get('part1')+" "+item.get('part2')+"&lt;/li&gt;"); } }); var listView = new ListView(); })(jQuery); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload