Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7021607
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T23:28:22+00:00 2026-05-27T23:28:22+00:00

This is an example of Backbone.js code (taken from this tutorial): // **This example

  • 0

This is an example of Backbone.js code (taken from this tutorial):

// **This example illustrates the binding of DOM events to View methods.**
//
// _Working example: [2.html](../2.html)._  
// _[Go to Example 3](3.html)_

//
(function($){
  var ListView = Backbone.View.extend({
    el: $('body'), // el attaches to existing element
    // `events`: Where DOM events are bound to View methods. Backbone doesn't have a separate controller to handle such bindings; it all happens in a View.
    events: {
      'click button#add': 'addItem'
    },
    initialize: function(){
      _.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here

      this.counter = 0; // total number of items added thus far
      this.render();
    },
    // `render()` now introduces a button to add a new list item.
    render: function(){
      $(this.el).append("<button id='add'>Add list item</button>");
      $(this.el).append("<ul></ul>");
    },
    // `addItem()`: Custom function called via `click` event above.
    addItem: function(){
      this.counter++;
      $('ul', this.el).append("<li>hello world"+this.counter+"</li>");
    }
  });

  var listView = new ListView();      
})(jQuery);

I don’t understand why it has to be preceded by an (function($){....

Can anyone explain this to me?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T23:28:23+00:00Added an answer on May 27, 2026 at 11:28 pm

    This is common practice when authoring jQuery plugins.

    The reason is that you want to avoid conflicts with other libraries that may also use the $ symbol in the global scope. By wrapping your code in a function call that takes one argument (named $) and pass the jQuery object into that function, you ensure that you avoid conflicts.

    function($) { // declare an anonymous function that takes an argument $
    
        // conflict safe code =)
    
    }(jQuery); // pass the argument jQuery to the anonymous function
    

    As nielsbot noted, it might be easier to see what the above code does if you give the function a name:

    var executeSafely = function($) {
    
        // conflict safe code =)
    
    }
    
    executeSafely(jQuery);
    

    I know this is way after the fact, but MikeG just pointed out in a comment on this post that this isn’t necessarily a bad thing to do with javascript code in other places as well. I thought I’d expand a little on why:

    A case for scoping

    Suppose you have two independent javascript modules on your web site. Let’s say you’ve written the code for them in the two js files module-one.js and module-two.js. Normally, you only have one module on a page, so when authoring one of them, you don’t care what happens in the other one (you might even have different developers working on the different modules independently of the other).

    Then, you decide it would be nice to show both these things on the start page, so you include the following in the head section of the start page html:

    <script type="text/javascript" src="module-one.js" />
    <script type="text/javascript" src="module-two.js" />
    

    [Cue: Doomsday music!] Everything breaks down! What the heck happened?

    You look in the code for the modules, and see the following:

    module-one.js:

    var state = 0;
    
    function init() {
        ...
    }
    
    etc...
    

    module-two.js:

    var state = 2;
    
    function init() {
        ...
    }
    
    etc ...
    

    What’s going on here?

    Well, the page loads the two scripts in order – first module-one.js is loaded, and everything is go for the first module; then, module-two.js is loaded, and overrides some of the variables defined in the first module! This is because defining a variable in the global scope in JavaScript, it is implicitly interpreted as defining it on the window object. Thus, if you run the two script files after each other, you, for example, first set window.state = 0, and then window.state = 2. As you see, the modules aren’t really independent. When, for example, init() (or, really, window.init()) is called after both scripts are loaded, only the second module is initiated – the first init() function was overwritten (since window can only have one property named init) and doesn’t exist anymore.

    Scoping to the rescue

    To avoid this problem, you should wrap your modules in function calls, just like you did with the jQuery plugin above. However, these function don’t need to take any arguments:

    module-one.js

    (function() {
        // code for module one here
    })();
    

    module-two.js

    (function() {
        // code for module two here
    })();
    

    Now, since the two modules are defined inside separate functions, all variables are scoped to live only within those functions. If you’re unsure how your JavaScript code will be used, wrapping it in a function call like this is good practice to avoid conflicts. And since it can be hard to remember good practices if you don’t follow them all the time, following this one all the time really doesn’t hurt anyone =)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This example is taken from w3schools . CREATE TABLE Persons ( P_Id int NOT
I am using very similar code to the Backbone ToDo example - http://documentcloud.github.com/backbone/docs/todos.html .
This example is from php.net: <?php function Test() { static $a = 0; echo
Trying to get my head around backbone.js. This example is using Backbone Boilerplate and
I'm learning Backbone.js and got stuck on this simple example. Could you explain what's
tutorial: http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/ I am going through the CloudEdit rails/backbone.js tutrorial and got stuck on
I'm trying to follow this Rails/Backbone example but they are using erb and not
In the example Todos app for backbone.js, this takes place: clearCompleted: function() { _.each(Todos.done(),
Using a Backbone.js View, say I want to include the following events: events: {
I've been following the cloudedit tutorial http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/ for adding backbone to my rails app,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.