将当前对象传递给回调函数的最佳方法是什么?
我一直在使用类似的东西:
var that = this;
例如:
<link rel="import" href="/bower_components/polymer/polymer.html">
<polymer-element name="stackx-example">
<template>
<div id="container">{{innards}}</div>
</template>
<script>
Polymer('stackx-example', {
ready: function() {
var jax = new XMLHttpRequest();
jax.open('GET', '/jaxson/testing/', true);
jax.send();
var that = this;
jax.onreadystatechange = function(){
if (jax.readyState == 4 && jax.status == 200) {
that.innards = jax.responseText;
}
}
},
innards: '..missing'
});
</script>
</polymer-element>
答案 0 :(得分:1)
您可以使用Function.prototype.bind()
将回调中的this
值设置为回调之外使用的相同this
值:
jax.onreadystatechange = function() {
if (jax.readyState == 4 && jax.status == 200) {
this.innards = jax.responseText;
}
}.bind(this);
作为一个切线,这是一个使用<core-ajax>
而不是普通XMLHttpRequest
的绝佳机会。它将导致更多惯用的聚合物代码:
<polymer-element name="stackx-example">
<template>
<div id="container">{{innards}}</div>
<core-ajax auto
url="/jaxson/testing/"
handleAs="text"
response="{{innards}}">
</core-ajax>
</template>
<script>
Polymer({
innards: '..missing'
});
</script>
</polymer-element>
答案 1 :(得分:0)
另一种选择(ES6),对我有效,而无需bind()
jax.onreadystatechange = ()=>{
if (jax.readyState == 4 && jax.status == 200) {
this.innards = jax.responseText;
}};