gpt4 book ai didi

javascript - polymer 1.x : Event listener scope of "this" object

转载 作者:行者123 更新时间:2023-11-30 08:33:29 25 4
gpt4 key购买 nike

我已经为我的 <iron-ajax> 添加了一个事件监听器到我的自定义元素中打电话。

问题

How to I reference the last-response property of the <iron-ajax> element from an imperatively defined event listener?

请参阅下面代码中的注释。

自定义元素.html
<template>
...
<iron-ajax id="ajax" last-response="{{ajax}}"></iron-ajax>
...
<template>
<script>
...
var t = this.$.ajax;
t.addEventListener('response', function(e) {
console.log(this.ajax); // undefined
console.log(e); // Successfully logs response event object to console
});
...
</script>

最佳答案

使用 Javascript bind() 改变函数中 this 的上下文:

var t = this.$.ajax;
t.addEventListener('response', function(e) {
console.log(this); // this now = t
console.log(e); // Successfully logs response event object to console
}).bind(t);

参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

关于javascript - polymer 1.x : Event listener scope of "this" object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34505580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com