简体   繁体   中英

How to get properties of the object subjected to event using Fabric.js?

Using Fabric.js 1.1.6, I have the following:

var rect = new fabric.Rect({});
rect.on('moving', function(obj) {
    // I want to retrieve and set properties from the
    // object rect from inside this event function
});
  • Is it possible to retrieve and modify the rect properties from inside the function called by the event?
  • If it is, how do I do that?
  • If it is not, any suggestions on how could I modify rect properties from inside the event function?

Thank you in advance!

--

Update: The above question is correctly answered by @plalx, but I actually have this in a greater context:

function SomeClass()
{
    this.rect = new fabric.Rect({});
    this.rect.on('moving', function(obj) {
        // here, this.rect is undefined
    });
}

Well, in the latter context, I can't only use this.rect inside the function, because there this refers to the function, not to SomeClass.

How about now, what are the answers for the three questions above?

"Is it possible to retrieve and modify the rect properties from inside the function called by the event?"

Not only it is possible but it is very simple ;) You should read about closures in JavaScript.

For question #1

var rect = new fabric.Rect({});
rect.on('moving', function(obj) {
    rect.someProperty = 'test';
});

For question #2

function SomeClass() {
    var rect = this.rect = new fabric.Rect({});

    this.rect.on('moving', function(obj) {
        // here, this.rect is undefined
        rect.someProperty;
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM