How to access $(this) with api.attachWidgetAction?


(Steven Slade) #1

I am adding a new post menu button with api.addPostMenuButton.

I would like to access the data of this post-menu button on click using api.attachWidgetAction.

Ideally, it would be the equivalent of:

$(this).attr('data-something')

Any ideas?


(Robin Ward) #2

You can’t access selectors like that when using the widget code (with a couple of exceptions).

The reason is the widgets can be re-rendered at any time and replaced with new HTML. So even if you added an attribute from some other process it would likely be painted over when it refreshed.

On the other hand, if you were able to create that data-* attribute as part of a decorator, you should already have it in attrs and you can access that in your action as this.attrs.


(Steven Slade) #3

Thanks for the explanation. Very helpful. :ok_woman:

Does api.attachWidgetAction have access to attrs (my guess is no since I tried with no luck). If no, how exactly would a post menu button action have access. Here’s an example of what I mean:

api.addPostMenuButton('drink-coffee', (attrs) => {
        return {
          action: 'drink-coffee',
          icon: 'coffee',
          className: 'drink-coffee',
          title: 'Coffee',
          data: {
            'coffee-link': attrs.shareUrl
          },
          position: 'first'
        };
      });

So here we want the action drink-coffee to link to the data-coffee-link as defined in the addPostMenuButton. Since attachWidgetAction does not have access to attrs (assumingly), where would we put some good ol’ JS to link to the data-coffee-link.

Apologies for basically asking for a tutorial :bow:


(Robin Ward) #4

Yes you can use this.attrs to access the attributes within your action. If it’s not working, make sure you’re not using the ES2015 fat arrow function syntax, as it preserves this from the outer scope, which is NOT what you want in this case.

For example:

api.attachWidgetAction('post', 'annoyMe', function() {
   // this.attrs is the attrs
});