How to refer to `api.addPosterIcon` from inside of a function

AI-generated summary

The discussion revolves around an issue with referring to api.addPosterIcon from inside a function in a text/discourse-plugin script. Ilia provided an example code snippet where api.addPosterIcon works when moved to the top level but silently fails when run from inside the extract_associated_user_data function. blattersturm analyzed the implementation of text/discourse-plugin snippets and suggested that the issue might not be related to JavaScript’s implicit this or api going out of scope. Ilia wondered why api.getCurrentUser() works fine from inside the function while api.addPosterIcon does not, and expressed a preference for using native API solutions over custom code.

Hi,

Could anyone please advise how to refer to api.addPosterIcon from inside of a function?

Example:

<script type="text/discourse-plugin" version="0.8">
   api.onPageChange(url => {
       if (Discourse?.currentUser?.admin) {
           extract_associated_user_data();
       }
   });
   function extract_associated_user_data() {
       // lots of code above, and now we ready to call `addPosterIcon` func
       api.addPosterIcon(function(data, attrs) {
            return { icon: 'user', className: 'customer' };       
       });
   }
</script>

If api.addPosterIcon moved to the top level, it works, however when run from inside of extract_associated_user_data it’s just silently does nothing (not getting run). Perhaps, this is getting messed up internally but I am not sure how to refer to it anyway. I’ve tried a lot of things before posting it.

I hope it will also be useful for future dev readers.

We run latest version of Discourse 2.8.0.beta6 (cba8b39607).

The implementation of text/discourse-plugin snippets in themes is apparently as follows:

I’m not directly seeing any mention of a this instance here, which would imply it’s not related to JS’ implicit this, nor can it be api going out of scope, as the snippet is pasted in there.

Does this minimal example actually work, i.e. is it not an issue with the omitted code?

FWIW: the Discourse global and its currentUser field could be replaced with api.getCurrentUser() as well here:

Great, thanks.

I wonder why api.getCurrentUser() works just fine from inside of the function while api.addPosterIcon still not?

I would like to try to use native API as much as possible rather than writing custom code solutions (which isn’t a problem at all).