[英]Polymer 1.x: Event listener scope of “this” object
我在<iron-ajax>
調用的自定義元素中添加了事件偵聽器。
如何從命令式定義的事件偵聽器中引用
<iron-ajax>
元素的last-response
屬性?
請參見下面的代碼中的注釋。
custom-element.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綁定()來改變的情況下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/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
this
對象包含在事件偵聽器的范圍內。
引入一個名為的新變量that
並按如下所示應用必要的范圍。
var that = this, // Adds scope t = this.$.ajax; t.addEventListener('response', function(e) { console.log(that.ajax); // Successful reference });
我找到了解決此問題的兩種方法。
首先(當我具有鐵質ajax形式時,將事件偵聽器附加到自定義元素,並使其從內部元素冒泡
所以
this.addEventListener('iron-form-response',function(e) {
//this is correct here
});
另一種方法,當我自己使用Iron Ajax時使用(即,調用this.$.ajax.generateRequest();
是在我的元素上設置一個函數以獲取響應-所以
<iron-ajax
id="validateuser"
url="/api/validate_user"
handle-as="json"
method = "POST"
body = "[[user]]"
content-type="application/json"
on-response="_validate"></iron-ajax>
然后在_validate
內部,它仍然引用我的自定義元素。 在這種情況下,我不需要last_response,因為這樣找到響應
_validate: function(e) {
var response = e.detail.response;
this.$.spinner.cancel();
if (response.status) {
//this user validated, so we are logged on
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.