管理“此"在事件/回调驱动的JavaScript应用程序中 [英] Managing "this" in event/callback driven JavaScript applications

查看:65
本文介绍了管理“此"在事件/回调驱动的JavaScript应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在jQuery和Backbone.js之类的框架中经常使用的回调中处理"this"引用的预期方法是什么

I was wondering what is the intended method for dealing with "this" references in callbacks frequently used in frameworks like jQuery and Backbone.js

这是我在使用Backbone.js和jQuery UI时遇到的简化示例,但这并不是真正针对这些框架的.

Here is the simplified example I'm having a problem with, using Backbone.js and jQuery UI, but it is not really specific to these frameworks.

var MyView = Backbone.View.extend({
   render: function() {
      $('#mybutton').click(function() {
         // My code in here
      });
   },

   callMe: function() {
      alert('Rawr!');
   }
});

现在,我该如何从点击处理程序中引用MyView实例?例如,如何在点击处理程序内部调用"callMe"?在处理程序之外,我只是调用this.callMe();但是"this"将替换为点击处理程序中的DOM元素.解决此问题的最佳方法是什么?

Now, how would I go about referencing the instance of MyView from inside the click handler? For example, how would I call "callMe" from inside the click handler? Outside the handler I'd just call this.callMe(); but "this" gets replaced with the DOM element inside the click handler. What is the best way to approach this?

推荐答案

最有效的方法是将this的结果存储在另一个变量中,然后在回调中使用它;

The most effective way is simply to store the result of this in another variable, and then use that within the callback;

var MyView = Backbone.View.extend({
   render: function() {
      var that = this;

      $('#mybutton').click(function() {
          // use that for MyView and this for the DOM element
      });
   },

   callMe: function() {
      alert('Rawr!');
   }
});

或者,您可以使用 jQuery.proxy() 或HTML 5( Function.prototype.bind() 方法来定义this的值.显然,您将失去使用this来引用DOM元素的能力,因此必须依靠Event对象的target属性;

Alternately, you can use either jQuery.proxy() or the HTML 5 (beware of backwards compatability) Function.prototype.bind() method to define the value of this. Obviously then you'd loose the ability to use this to refer to the DOM element, so would have to rely on the target property of the Event object;

var MyView = Backbone.View.extend({
   render: function() {
      $('#mybutton').click((function(e) {
          // Use `this` for MyView and `e.target` for the DOM element
      }).bind(this));
   },

   callMe: function() {
      alert('Rawr!');
   }
});

或者:

var MyView = Backbone.View.extend({
   render: function() {
      $('#mybutton').click(jQuery.proxy(function(e) {
          // Use `this` for MyView and `e.target` for the DOM element
      }, this));
   },

   callMe: function() {
      alert('Rawr!');
   }
});

这篇关于管理“此"在事件/回调驱动的JavaScript应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆