[英]Javascript: keep object 'this' scope within an event handler
I have a Stream
object taking care of an XML request: 我有一个Stream
对象,负责处理XML请求:
/**
* Init stream class.
*
* @param array actions
* @param object options
* @return void
*/
var Stream = function(actions, options)
{
this.actions = !actions ? [] : actions;
this.options = options;
}
/**
* Stream completion handler.
*
* @param object evt
* @return void
*/
Stream.prototype.complete = function(evt)
{
console.log(this);
// this is not the Stream object we're within,
// instead it's the XMLHttpRequest object :(
}
/**
* Start flowing the stream!
*
* @param void
* @return void
*/
Stream.prototype.flow = function()
{
var req = new XMLHttpRequest();
req.addEventListener('load', this.complete);
req.open('GET', '/stream.php');
req.send();
}
new Stream([], {}).flow();
Problem is, on the load
event listener - when I try to console log this
(wanting to refer to Stream
) - I get the XMLHttpRequest
object instead. 问题是,在load
事件侦听器上-当我尝试控制台记录this
日志(想要引用Stream
)时,我改为获取XMLHttpRequest
对象。 How do I go about retrieving my scope? 我该如何找回我的范围?
As you can tell, Vanilla JS is not my forte, but I've decided to work on it ;) 如您所知,Vanilla JS不是我的强项,但我决定继续努力;)
Guidance appreciated! 指导表示赞赏!
add var that = this;
添加var that = this;
before registering event and in event handler use console.log(that);
在注册事件之前和在事件处理程序中,使用console.log(that);
Use the following code to modify .complete()
using .bind()
: 使用以下代码使用.bind()
修改.complete()
.bind()
:
req.addEventListener('load', this.complete.bind(this));
When the request object uses your this.complete
function, it invokes it with the context of the request object ( XMLHttpRequest
instance). 当请求对象使用this.complete
函数时,它将与请求对象的上下文( XMLHttpRequest
实例)一起调用它。
this.complete.bind(this)
makes a new bound function that makes sure to have this
an instance of Stream
. this.complete.bind(this)
,使一个新的绑定功能,可确保有this
的实例Stream
。
You can check more about this problem in the following article . 您可以在以下文章中检查有关此问题的更多信息。
另一种方法可能是:
req.addEventListener('load', function(e){e.target.complete()});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.