0

I´m looking a sample of a backbone / require.js app.

I have the following code:

define([
  'jquery',
  'underscore',
  'backbone',
  // Pull in the Collection module from above,
  'models/project/ProjectModel',
  'collections/projects/ProjectsCollection',
  'text!templates/projects/projectsListTemplate.html'

], function($, _, Backbone, ProjectModel, ProjectsCollection, projectsListTemplate){
  var ProjectListView = Backbone.View.extend({
    el: $("#projects-list"),

    render: function(){

      var data = {
        projects: this.collection.models,
        _: _ 
      };

      var compiledTemplate = _.template( projectsListTemplate, data );
      $("#projects-list").html( compiledTemplate ); 
    }
  });
  return ProjectListView;
});

Someone could explain me the meaning of the code bellow?

_: _ 
RMontes13
  • 2,138
  • 3
  • 16
  • 23
  • 1
    It's reference to underscore object passed to template arguments. Basically guys do this for perfomance reason and sometimes for resolve naming conflicts. It's quite similar to this question: http://stackoverflow.com/questions/2716069/how-does-this-javascript-jquery-syntax-work-function-window-undefined just assume that you pass _ or $ instead of window. As for me, it's a microoptimization and you will probably never see speed boost. – Tommi Jul 09 '13 at 10:18

1 Answers1

2

Short answer: They're assigning _ a value of _ in the data object. Just like projects is assigned this.collection.models.

Longer answer: By doing this you're creating a local reference to _ so when the program is executed it doesn't have to look as far up the scope tree to find _. However, this really isn't needed as it most likely won't have any visible impact on performance.

The thing is there are a million other much larger bottlenecks so you'll most likely never notice the difference. For example, your example uses the require.js test.js plugin which loads external files on demand. However, that means before that text template can be used by your application it has to successfully complete a GET request. Which means the application probably has to wait anywhere from 10ms to 200ms before it can do anything with the template. So, any performance gains by using _:_ are blown out of the water by that alone.

Isaac Suttell
  • 469
  • 3
  • 9