简体   繁体   中英

fabric.js assign event listener to an object for multiple events

I am asking this mainly out of curiosity as it is possible to replicate code but being deep in rails at the minute, repetition makes me feel dirty and I can't find it in the docs.

Suppose I have a rect = fabric.Rect and I wanted to add a listener for say, moving and modified that do the same thing:

rect.on('moving', function() {
    console.log('moving or modified'); 
});

rect.on('modified', function() {
    console.log('moving or modified'); 
});

is it possible to combine these in some way?

I'm very new to JS and so this could be a simple thing in JS that I've not come across yet but again, it's not mentioned in Fabric docs that I've seen.

I'm a little late, but just in case anyone else has this problem - you just need to move your common code into a function, and then pass key/value pairs to the on() function:

function doLog() {
    console.log('moving or modified');
}

rect.on({
    'moving': doLog,
    'modified': doLog
});

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