繁体   English   中英

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

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

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

先感谢您!

-

更新:上面的问题已通过@plalx正确回答,但实际上我在更大的范围内有此问题:

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

那么,在后一种情况下,我不能只在函数内部使用this.rect,因为this指的是功能,而不是SomeClass的。

现在,以上三个问题的答案如何?

“是否可以从事件调用的函数内部检索和修改rect属性?”

不仅可能,而且非常简单;)您应该阅读有关JavaScript中的闭包的信息。

对于问题1

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

对于问题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