0

我正在做一个非常简单的 Backbone 应用程序示例,并且不断收到 JS 错误消息。我基本上有两个文件:

  1. 应用程序.js

此文件创建一个 Backbone.js 应用程序,该应用程序使用集合视图中的数据将模板中的 span 附加到 html 文件上已创建的 div 中。

    /*Backbone.js Appointments App*/

    App = (function($){
      //Create Appointment Model
      var Appointment = Backbone.Model.extend({});

      //Create Appointments Collection
      var Appointments = Backbone.Collection.extend({
        model: Appointment
      });

      //Instantiate Appointments Collection
      var appointmentList = new Appointments();
      appointmentList.reset(
        [{startDate: '2013-01-11', title: 'First Appointment', description: 'None', id: 1},
         {startDate: '2013-02-21', title: 'Second Appointment', description: 'None', id: 2},
         {startDate: '2013-02-26', title: 'Third Appointment', description: 'None', id: 3}
        ]
      );

      //Create Appointment View
      var AppointmentView = Backbone.View.extend({
        template: _.template(
          '<span class="appointment" title="<%= description %>">' +
          ' <span class="title"><%= title %></span>' +
          ' <span class="delete">X</span>' +
          '</span>'
        ),

        initialize: function(options) {
          this.container = $('#container');
        },

        render: function() {
          $(this.el).html(this.template(this.model));
          this.container.append(this.el);
          return this;
        }
      });

      var self = {};
      self.start = function(){
        new AppointmentView({collection: appointmentList}).render();
      };
      return self;
    });

    $(function(){
      new App(jQuery).start();
    });
  1. 索引.html

该文件仅调用 jquery、backbone 和其他 js 库,还创建了 div 容器,前一个文件中的 Backbone.js 应用程序将在其中附加数据。

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>hello-backbonejs</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
      <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
      <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
      <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
      <script src="app.js" type="text/javascript"></script>
    </head>
    <body>
    <div id="container"></div>
    </body>
    </html>

我得到的错误如下:

Uncaught TypeError: Object [object Object] has no method 'reset' app.js:14
App app.js:14
(anonymous function) app.js:49
e.resolveWith jquery.min.js:16
e.extend.ready jquery.min.js:16
c.addEventListener.z jquery.min.js:16
4

1 回答 1

2

您使用 Backbone 0.3.3,但Collection.reset在 Backbone 0.5 中引入。有关更多信息,请参阅更改日志

要么升级 Backbone(目前是 0.9.9)(以及使用 Underscore 和 jQuery),或者Collection#refresh如果你绝对必须保留 Backbone 0.3.3(但你可能会在路上遇到其他错误)。

于 2013-01-11T11:27:39.847 回答