在 backbone 视图中单击 "this"

Click on "this" in a backbone view

我是 backbone 的新手,我的事件系统有点问题。

我有一个代表 li 元素的视图,我想在点击它时做一些事情。

这是我的代码:

var IndicatorView = Backbone.View.extend({
  tagName: 'li',
  className: 'indicator',
  initialize: function(options){
    _.extend(this, _.pick(options, "controller"));
    this.model.on('change', this.render, this);
    var self=this ;
    this.$el.on("click", function(){
      alert(self.model.get('name'));
    })
  },
  render: function(){
    this.$el.html(this.model.get('name'));
    return this; // enable chained calls
  }
});

目前,它有效,但使用 jQuery 个事件。我怎样才能对 backbone 事件做同样的事情?感谢您的回答:)

使用空选择器将事件绑定到视图 el:

var IndicatorView = Backbone.View.extend({
    tagName: 'li',
    className: 'indicator',

    events: {
        'click': function() {
            alert(this.model.get('name'));
        }
    },

    initialize: function(options){
        _.extend(this, _.pick(options, "controller"));

        // listenTo is recommended over on
        // http://backbonejs.org/#Events-listenTo
        this.listenTo(this.model, 'change', this.render);
   },
   render: function(){
       this.$el.html(this.model.get('name'));
       return this; // enable chained calls
   }
});

有关详细信息,请参阅 http://backbonejs.org/#View-delegateEvents