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?
The discussion revolves around accessing post-menu button data with api.attachWidgetAction. stevenpslade initially asks how to access $(this).attr('data-something') when using api.attachWidgetAction. eviltrout explains that widgets can be re-rendered, making it unreliable to access attributes directly. Instead, attributes can be accessed through this.attrs within the action.
stevenpslade shares an example of adding a post-menu button with api.addPostMenuButton and asks how to access the data-coffee-link attribute in the action. eviltrout clarifies that this.attrs can be used to access attributes within the action, but notes that using ES2015 fat arrow function syntax can prevent this from being set correctly. A code example is provided to demonstrate the correct usage of this.attrs.
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?
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.
Thanks for the explanation. Very helpful. ![]()
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 ![]()
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
});