I'm using fabric.js and at one point I used the following code:
canvas.on("object:modified", (opt) => { console.log(opt.action); //="scale" handleScaled(opt); });
But in the handleScaled
function opt.action
is undefined:
function handleScaled(opt) { console.log(opt.action) //=undefined console.log(opt) //displays the whole opt object but there is no "action" in it //further handleScaled code }
console.log(opt.action)
before the function call displays "scale" correctly, but when I call the same in handleScaled
, opt .log(opt.action) will display "scale" correctly. Operation
is undefined.
Why does opt.action
not seem to exist within the scope of the called function, but exists just before the call?
Correct working code only calls handleScale
when the operation is "scale":
canvas.on("object:modified", (opt) => { if (opt.action === "scale") { handleScaled(opt); } });
In your code, when you log
opt.action
before calling thehandleScaled
function, it will correctly display "scale" because it is accessing theaction
The code> attribute of theopt
object passed to the callback function of thecanvas.on
event handler. When you logopt.action
in thehandleScaled
function, it appears asundefined
because theopt
object is passed toThe handleScaled
function is another instance of this object. It does not have anaction
attribute because it is different from theopt
object recorded previously.To make
opt.action
accessible in thehandleScaled
function, you can modify the code like this:By passing the
opt
object directly to thehandleScaled
function, you retain access to its properties within the function scope. Ensure that theopt
object passed tohandleScaled
contains the expectedaction
properties.