Girardi
Girardi

Reputation: 2809

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
});

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?

Upvotes: 0

Views: 2135

Answers (1)

plalx
plalx

Reputation: 43728

"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;
    });
}

Upvotes: 3

Related Questions