简体   繁体   English

如何使用Fabric.js获取受事件影响的对象的属性?

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

Using Fabric.js 1.1.6, I have the following: 使用Fabric.js 1.1.6,我有以下内容:

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? 是否可以从事件调用的函数内部检索和修改rect属性?
  • 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? 如果不是,关于如何从事件函数内部修改rect属性的任何建议?

Thank you in advance! 先感谢您!

-- -

Update: The above question is correctly answered by @plalx, but I actually have this in a greater context: 更新:上面的问题已通过@plalx正确回答,但实际上我在更大的范围内有此问题:

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. 那么,在后一种情况下,我不能只在函数内部使用this.rect,因为this指的是功能,而不是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?" “是否可以从事件调用的函数内部检索和修改rect属性?”

Not only it is possible but it is very simple ;) You should read about closures in JavaScript. 不仅可能,而且非常简单;)您应该阅读有关JavaScript中的闭包的信息。

For question #1 对于问题1

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

For question #2 对于问题2

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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