Tengo una clase simple en Javascript y me encontré con un problema estúpido. ¿Me estoy perdiendo algo fundamental en JS?
En la siguiente clase, las funciones constructor, initialize y setImage funcionan perfectamente. Tanto "initialize" como "setImage" usan la variable "this" para acceder a las propiedades de la clase.
En todas las pequeñas funciones "onChangeXXX" en la parte inferior, aparece un error que indica que "esto" es nulo y, por lo tanto, no puede encontrar las propiedades como "filtros".
Cuando uso esta clase, también puedo enlazar desde una aplicación Vue (desde fuera de la clase) a los "SliderValues" y cambian de manera apropiada y el código externo puede llamar a los métodos onChange.
El único problema en este momento parece ser que esta variable en los métodos onChange es nula, pero no puedo entender por qué es así.
import { fabric } from "fabric"; export default class FabricSvc { constructor( ref ) { this.imageRef= ref , this.canvas= new fabric.Canvas(ref), this.image= null, this.filters= { brightness: new fabric.Image.filters.Brightness(), saturation: new fabric.Image.filters.Saturation(), contrast: new fabric.Image.filters.Contrast(), hue: new fabric.Image.filters.HueRotation(), }; this.sliderValues= { brightness: 0, saturation: 0, contrast: 0, hue: 0, }; } initialize() { var rect = new fabric.Rect({ fill: "red", width: 20, height: 20 }); this.canvas.add(rect); } setImage(base64Image) { var imageUrl = "data:image/gif;base64," + base64Image; var that = this; fabric.Image.fromURL(imageUrl, function(oImg) { that.image = oImg; that.image.filters.push(that.filters.brightness); that.image.filters.push(that.filters.saturation); that.image.filters.push(that.filters.hue); that.image.filters.push(that.contrast); that.canvas.add(oImg).renderAll(); that.canvas.setActiveObject(that.image); }); } onChangeBrightness() { var that = this; that.filters.brightness.brightness.value = that.sliderValues.brightness; that.image.ApplyFilters(); } onChangeSaturation() { this.filters.saturation.saturation.value = this.sliderValues.saturation; this.image.ApplyFilters(); } onChangeHue() { this.filters.hue.hue.value = this.sliderValues.hue; this.image.ApplyFilters(); } onChangeContrast() { this.filters.contrast.contrast.value = this.sliderValues.contrast; this.image.ApplyFilters(); } }Si hace la diferencia, llamaré esto desde VueJs (Vue2) con esto:
<input type="range" min="-1" max="1" step="0.01" v-model="fabricSvc.sliderValues.contrast" @change="fabricSvc.onChangeBrightness" />Sin embargo, dudo que el lado de Vue tenga algo que ver con el problema.