Sublime Forum

EventListener on_post_save callback

#1

I have the following class:

class class1(sublime_plugin.EventListener):
    def __init__(self):
        // init global
        
    def on_post_save(self, view):
        // modify global

    def read(self):
        // access global

I’ve noticed that all of my changes in on_post_save() are lost on read(). I compared the object id’s and It appears that the callback is fired with a different instance of the class than the one who used to init and read(). I thought EventListeners are only instantiated once?

0 Likes

#2

This is the case except you save your plugin which contains the EventListener. Saving the plugin will cause ST to reload it and create a new listener instance.

Btw.: Who is calling read()? Is it called by an on_... method?

0 Likes

#3

read is called by an application command

0 Likes

#4

How can it work? You don’t know the object instance of the listener as it is known by ST only.

The class1 you’ve created is a class not an object. If your plugin is loaded by ST, the core creates an object of class1 and stores it in sublime_plugin.view_event_listeners dictionary. Without hacking that, you don’t have access to that object being created for your package. Therefore you can’t call read() from any other object.

The only way to do so was to add an on_text_command() handler to class1 and call read from that, if the command_string matches. But even this is bad practice.

import sublime_plugin


class class1(sublime_plugin.EventListener):
    def __init__(self):
        self.test = "hello world"

    def on_text_command(self, view, command, args):
        if command == 'my_text_command':
            self.read()

    def on_post_save(self, view):
        self.test = "hello you"

    def read(self):
        print(self.test)
        print(self)

The EventListener is a standalone interface class. You can use it to call your functions on certain events but you should/must not use it as class being accessed by your functions!

0 Likes

#5

I think it worked because I created an instance of class1 inside my code in plugin_loaded()… From your explanation I see that this essentially created 2 event listeners and is bad practice. Thanks for the clarification.

0 Likes

#6

ST doesn’t use a local instance of that class(es). It iterates through all loaded modules and creates its its own objects for each class derived from one of the Command / Listener classes.

The EventListener class is just an interface.

1 Like