简体   繁体   English

将此关键字与javascript原型addEventListener一起使用

[英]using this keyword with javascript prototype addEventListener

I want to use this keyword in event listener function. 我想在事件监听器函数中使用此关键字。

var MyViewModel = function (file) {
    this.status = "";

    this.xm = new XMLHttpRequest();    
    this.xm.addEventListener("load", this.onLoad, false);
};

MyViewModel.prototype.onLoad = function (e) {
    this.status = "ok";
};

I can not access the MyViewModel object with this keyword in onLoad prototype. 我无法在onLoad原型中使用关键字访问MyViewModel对象。

  • this object is window . 这个对象是窗口
  • e parameter is XmlHttpRequest e参数是XmlHttpRequest

How can I access this? 我该如何访问?

You can solve this problem with jQuery.proxy 您可以使用jQuery.proxy解决此问题

This is specifying function scope. 这是指定功能范围。

var MyViewModel = function (file) {
    this.status = "";

    this.xm = new XMLHttpRequest();    
    this.xm.addEventListener("load",  $.proxy(this.onLoad, this), false);
};

MyViewModel.prototype.onLoad = function (e) {
    this.status = "ok";
};

Now you can use this keyword as MyViewModel. 现在,您可以将此关键字用作MyViewModel。

Without jQuery you could also do something like: 没有jQuery,您还可以执行以下操作:

function MyViewModel(file) {
    this.status = "";
    this.xm = new XMLHttpRequest();   
    var viewModel = this;
    this.xm.addEventListener("load", function(){viewModel.onLoad()}, false);
}

so that a reference to the instance is held in a closure using viewModel and then used to set this to the required value in the call. 以便对实例的引用是在封闭件使用视图模型保持,然后用于将设置为在该呼叫所需的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM