1

I have jquery.js, backbone.js ,underscore.js inlcuded in my html header (I can see these files from browser)

 <script type='text/javascript'>
    (function($){
     var Student= Backbone.Model.extend({
          initialize: function(){
              console.log("studentis createrd");
          }
      });

        var students= Backbone.Collection.extend({
            model: Student
        });  

        console.log(students.models);
    })(jQuery);
</script>

I got this error message enter image description here

UPDATE:html header

<script src="/static/js/jquery.js" type="text/javascript"> </script>
<script src="/static/js/backbone.js" type="text/javascript"></script>
 <script src="/static/js/underscore.js" type="text/javascript"></script>
4

3 回答 3

7

First you need to make sure that Backbone is loaded properly --

The order should be

   ---> jQuery
   ---> underscore
   ---> backbone

Next need to create a new instance of the collection

You cannot operate directly on the Model or Collection before creating an instance of it.

(function ($) {
    var Student = Backbone.Model.extend({  // Created a Student model
        initialize: function () {
            console.log("studentis createrd");
        }
    });

    var Students = Backbone.Collection.extend({  // Create a Students collection
        model: Student
    });

    var student = new Student(); // Create a instance of Student model

    var students = new Students(); // New instance of Students collection
    students.add(student);   // Add a model to the collection

    console.log(students.models);
})(jQuery);

Check Fiddle

于 2013-05-23T18:51:09.853 回答
1

I think you also need to pass backbone as parameter to you function along with jQuery

 <script type='text/javascript'>
    (function($,Backbone){
     var Student= Backbone.Model.extend({
         initialize: function(){
            console.log("studentis createrd");
         }
      });

      var students= Backbone.Collection.extend({
         model: Student
      });  
     console.log(students.models);
      })(jQuery,Backbone);
</script>
于 2013-05-23T19:35:52.230 回答
1

Per my comment:

When are you importing the backbone file?

Backbone has a dependency on underscore to work, so you need to have Jquery -> Underscore -> Backbone in order for backbone to load properly.

于 2013-05-23T19:41:25.280 回答