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

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).