JQuery: 'this'在JQuery-Event-Handler中无法访问

backbone.js + JQuery: 'this' reference not accessible in JQuery-Event-Handler

本文关键字:访问 this JQuery JQuery-Event-Handler      更新时间:2023-09-26

我试图在我的webapp中使用backbone.js。我有一个视图,它使用JQuery draggable插件使div可拖动:

var ExampleView = Backbone.View.extend({
  events: {
    //...
  },
  initialize: function() {
    _.bindAll(this, "render");
    this.model.bind('change', this.render);
  },
  render: function() {
      // icanhaz
      this.el = ich.kinectdevtmpl();
      $(this.el).draggable({
         drag: function() { 
                alert(this.model);
         }
      });           
    return this;
  }      

});

但是在拖拽事件处理程序中,我无法访问'this。Model ',因为'this'不再指向视图。那么,我如何在JQuery事件处理程序中访问我的视图?

这已经改变了,不再是您想要的。你可以把它赋值给一个变量,然后使用它。

var that = this;
$(this.el).draggable({
   drag: function() { 
          alert(that.model);
   }
});