[英]Object-method callback loses its binding in an event handler when passed as a parameter, but not when hard-coded
[英]Object in Angular Component not defined in handler when its event calls callback
我在玩createjs和angular。 加載圖片時,我正在嘗試更新舞台。 我相信我在這里遇到了一個Angular問題。 當Bitmap對象上的load事件完成並且其回調運行時,未定義stage對象。 實際上,創建事件的Bitmap對象被報告為未定義(請參見下面的示例代碼)。
HTML中的onClick等引發的事件不會遇到相同的問題,並且toString()方法返回有關該對象的一些信息。
我相信我在這里不了解DI原則或其他內容。 我已經玩了很多,卻找不到答案或想出解決方案。 感謝您的幫助。
Angular version information:
Angular CLI: 1.6.6
Node: 8.9.4
OS: win32 x64
Angular: 5.2.2
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
@angular/cli: 1.6.6
@angular-devkit/build-optimizer: 0.0.42
@angular-devkit/core: 0.0.29
@angular-devkit/schematics: 0.0.52
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.6
@schematics/angular: 0.1.17
typescript: 2.5.3
webpack: 3.10.0
通過以下方式安裝createjs:npm install createjs-module --save
import {Component, OnInit} from '@angular/core';
import * as createjs from 'createjs-module';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
bmp: createjs.Bitmap;
ngOnInit(): void {
this.bmp = new createjs.Bitmap('https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SIPI_Jelly_Beans_4.1.07.tiff/lossy-page1-220px-SIPI_Jelly_Beans_4.1.07.tiff.jpg');
this.bmp.image.onload = this.bmpOnLoad;
this.bmp.name = 'BmpName';
}
bmpOnLoad(): void {
console.log(this.bmp.toString());
}
}
控制台出現錯誤,提示Cannot read property 'toString' of undefined
感謝@ericmartinezr在gitter中的角度/角度。
Eric為我提供了以下代碼段,這些代碼段可解決以下事實:在回調中引用“ this”的屬性失敗:
this.bmp.image.onload = () => this.bmpOnLoad();
要么
this.bmp.image.onload = this.bmpOnLoad.bind(this);
我希望能對此做一個解釋。 是否沒有一個被引用的單例組件? 為什么回調可以通過其他方式訪問未初始化的對象?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.