Backbone.js 事件不会火

Backbone.js Events wont Fire

过去几天我一直在尝试触发事件,所以我将应用程序剥离回到基础,但我仍然运行无法触发事件的问题。

backbone 中的其他所有内容都很好,除此之外我希望有人能提供帮助。

目前在我看来

    define([
  'jquery',
  'underscore',
  'backbone',
  'models/SpecificationModel',
  'collections/SpecificationCollection',
  'text!templates/specification/specificationlisttemplate.html'
], function($, _, Backbone, specModel, specCollection, specTemplate){

  var Specifications = Backbone.View.extend({

      events: {
            'click a.btn': 'showAlert'
      },
      showAlert: function() {
            alert('fired');
      },
      initialize:function() {
            _.bindAll(this, 'render');
            var self = this;
            this.collection = new specCollection();
            this.collection.fetch({
              success: function () {
                self.render();
              }
            });
        },

        render: function(){
          var data = {
            specs: this.collection.toJSON()
          };
          var compiledTemplate = _.template(specTemplate);
          $("#backBoneContent").html(compiledTemplate(data));
        }
      });

  return Specifications;
});

HTML

    <div id="backBoneContent">
    //

                    <tr>
                        <td>
                            <a href="#review/1" class="btn">View </a>
                        </td>
                    </tr>
                        <td>
                            <a href="#review/2" class="btn>View </a>
                        </td>
                    </tr>
   //
   </div>

您没有指定 Backbone 应将视图 1 附加到的任何 el,因此无法委托事件和事件永不开火。

根据经验,切勿在您的视图中直接使用 jQuery 对象,使用 this.$el or this.$ 并将容器作为选项传递给您的视图:

在您的路由器中,

var specsView = new SpecsView({el: "#backBoneContent"});

在您看来

render: function() {
    ...
    this.$el.html(compiledTemplate(data));
}

1 注意访问$("#backBoneContent")对于Backbone没有特殊意义,它只是一个jQuery对象。