How add event listener to Figma currentPage
I wrote plugin with UI for Figma using figma-api and TypeScript. Project consist of two main files:
code.ts
for callingfigma-api
ui.html
with<script>...</script>
with plugin`s user interface.
My plugin is working with data of selection on current page, so I send from code.ts
into ui
data of for example this object:
figma.currentPage.selection[0]
How can I add event listener to figma.currentPage
? For example, if user selected some other element on figma board, figma.currentPage.selection
will change and I want to sent new data into ui
.
Have you any ideas?
I think this is the answer.
figma.on('selectionchange', () => {
console.log(figma.currentPage.selection);
});
https://www.figma.com/plugin-docs/api/properties/figma-on/
Probably not the best approach but rather a quick hack that works. I am looking for the same answer but for now, I do this.
Basically, assign an initial variable layer. Then, check every few seconds for a change and if var is different from the previous var then assign a new one.
I hope that helps until we get a normal way of doing this.
var selected;
selected = figma.currentPage.selection[0];
setInterval(() => {
var selectedNew = figma.currentPage.selection[0];
if (selected != selectedNew) {
selected = selectedNew;
}
}, 3000)