Reputation: 49
I have one Angular project which uses fabric.js for canvas. I have one problem in using event listener to the canvas object.
In the code below, I want to use the global variable "disabled" in the function "movehandler". "console.log(this.disabled)" does not work. It is shown as "undefined" in the console.
How can I use global variable in the function for canvas.
...
disabled = "yes";
...
ngAfterViewInit(){
this.canvas = new fabric.Canvas(this.canvasTerm);
console.log(this.canvas);
this.innerWidth = window.innerWidth;
this.innerHeight = window.innerHeight;
this.canvas.setHeight(this.innerHeight - 120);
this.canvas.setWidth(this.innerWidth - 120);
this.canvas.on('object:moving', function () {
console.log('Event object:moving Triggered');
});
var moveHandler = function (evt) {
var movingObject = evt.target;
//console.log("sss",movingObject.get('left'), movingObject.get('top'));
};
//handler for done modifying objects on canvas
var modifiedHandler = function (evt) {
var modifiedObject = evt.target;
console.log(this.disabled);
console.log( modifiedObject.id,"last",modifiedObject.get('left'), modifiedObject.get('top'));
};
var customEvtHandler = function (evt) {
console.log("I was triggered by a custom event.");
};
//or you register with key/value pairs
this.canvas.on({
'object:moving' : moveHandler,
'object:modified' : modifiedHandler,
'custom:event' : customEvtHandler
});
}
Upvotes: 2
Views: 3143
Reputation: 359
Try arrow function.
instead of:
function (evt) {
}
try this:
() => {
}
or
(evt) => {
}
Upvotes: 4
Reputation: 71
You can do it like this:
var scope = this;
var modifiedHandler = function (evt) {
var modifiedObject = evt.target;
console.log(scope.disabled);
};
Or using arrow function:
var modifiedHandler = (evt) => {
var modifiedObject = evt.target;
console.log(this.disabled);
};
**Note: You should not use var
everywhere, use let
instead for variables which are used only in a block. var
should be used for global variables.
Upvotes: 0