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

老子叫甜甜 提交于 2019-12-25 04:54:12

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/15916603/how-to-get-properties-of-the-object-subjected-to-event-using-fabric-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!