I need to detect changes in a canvas object from the FabricJs library .
I have the following code:
var canvas = this.__canvas = new fabric.Canvas('canvas', {isDrawingMode:true});
//I need to watch the changes here ->
canvas.toJSON();
I have tried using this Object.prototype.watch() as follows:
canvas.toJSON.watch('objects', function(){ //Do something});
But it doesn't work, does anyone have an idea how to solve what I need?
To observe an object, they are
Object.observe
neitherObject.watch
valid options because they are obsolete or not implemented, what you can do -manually- is to replace each of the properties with a getter and a setter that fulfills the function of intermediary between the property itself and the user of the property.In this broker, you invoke a callback function, where you handle the change event and can manipulate the value.
This is an example of how to do it manually.
Final note: while I was putting the finishing touches to this answer, I have seen the answer of @ElAsiduo and I think that for your specific problem it is, possibly, a better solution than this one, if what you want is to know if the object -as a whole- has changed but you don't care which specific property has changed ; since this method does not observe the object in depth (the internal properties of an array or object) but works superficially, on the "proper" properties of the object itself. To use it on an entire object you would have to do watch on each of the properties and it can be impractical. If you need an event when a property changes, this method will be more useful. Cheers!
Try using the following code:
Code taken from the following SO question, link .