How to find the sender of a subscribed event?


#1

Hi,

I’m trying to write a package which modifies the TextBuffer just before it is saved to the disk. I subscribed the TextBuffer::onWillSave() event. But in the callback function, how how can I find out which TextBuffer triggered this event?

Presumably there should be something like a sender() function? But I couldn’t find anything related to this in the documentation.

Thanks.


#2

This is what closures are for:

function addHandler(buffer) {
  let subscription = buffer.onWillSave(() => {
    // Do something to the contents of the buffer
    buffer.setText("Gotcha!")    
  })

  buffer.onDidDestroy(() => {
    subscription.dispose()
  })
}

Because JavaScript functions create closures, you can access the buffer and subscription variables inside the handlers.


#3

Thanks leedohm. It works perfectly.

I’m a C++ programmer, so not quite familiar with the fancy features in JavaScript.:yum:


#4

Newer versions of C++ include lambda functions and closures too :grinning: But yeah, they’re very new to C++ whereas JavaScript has had them for a long, long time.