Search code examples
backbone.js

Backbonejs: backbone is not defined error


Google Chrome developer tools console throws this error:

uncaught reference error: backbone is not defined 

When this html file containing javascript with library backbone.js:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Example Backbone APP</title>
  </head>
  <body>

    <script>
      Whisky = Backbone.Model.extend();
        firstWhisky = new Whisky({
        name : 'Blenders Pride'
      });
      Whiskies = Backbone.Collection.extend({
        Model:Whisky ,
        url:"#"
      });

      first_view = Backbone.View.extend({
        el : 'body',
        initialize : function() { 
          this.$el.empty();
          this.render();
        } , 

        render : function() { 
          this.$el.append("<h1>The Whisky APP</h1>");
          this.list_view = new List_view();
          this.$el.append(this.list_view.render().el);
          return this ; 
        }
      });
      List_view = Backbone.View.extend({ 
        tagName : 'ul' , 
        render : function() {
          this.$el.empty();
          this.$el.append("<li>Royal stag</li>");
          this.$el.append("<li>Signature </li> ");
          return this ; 
        }
      });
      index_view = new first_view();    
    </script>
    <script src="LIB/json2.js"></script> 
    <script src="LIB/underscore-min.js"></script>  
    <script src="http://code.jquery.com/jquery.js"></script>  
    <script src="http://backbonejs.org/backbone.js"></script> 
  </body>
</html>

What is the reason for this error?


Solution

  • You can't use Backbone before it's declaration.

    Put the <script> tags before your own javascript code.

    You must re-organize your javascript part like this :

    <script src="LIB/json2.js"></script> 
    <script src="LIB/underscore-min.js"></script>  
    <script src="http://code.jquery.com/jquery.js"></script>  
    <script src="http://backbonejs.org/backbone.js"></script> 
    <script>
      Whisky = Backbone.Model.extend();
        firstWhisky = new Whisky({
        name : 'Blenders Pride'
      });
      Whiskies = Backbone.Collection.extend({
        Model:Whisky ,
        url:"#"
      });
    
    
    
      first_view = Backbone.View.extend({
        el : 'body',
        initialize : function() { 
          this.$el.empty();
          this.render();
        } , 
    
        render : function() { 
          this.$el.append("<h1>The Whisky APP</h1>");
          this.list_view = new List_view();
          this.$el.append(this.list_view.render().el);
          return this ; 
        }
      });
      List_view = Backbone.View.extend({ 
        tagName : 'ul' , 
        render : function() {
          this.$el.empty();
          this.$el.append("<li>Royal stag</li>");
          this.$el.append("<li>Signature </li> ");
          return this ; 
        }
      });
      index_view = new first_view();    
    </script>