Posted 5 months ago. Visible to the public.

How to bind an event listener only once with Unpoly

You can use Unpoly's up.on Archive with a named listener function and immediately unbind this event listener with { once: true }:

Copy
up.on('up:fragment:inserted', { once: true }, function () { ... })

In Unpoly 1 you can immediately unregister the listener with up.off Archive :

Copy
up.on('up:fragment:inserted', function fragmentInsertedCallback() { up.off('up:fragment:inserted', fragmentInsertedCallback) // ... code for the callback function, which should run only once })

Example case

I had an Unpoly compiler for a tab navigation, which sets an -active class per default to the first tab link and removes it from all other tab links. If another tab link is clicked, the -active class switches to the clicked link.
In a Jasmine spec I wanted to test this behaviour.
Unpoly's up.hello Archive emits an up:fragment:inserted event, in whose callback function I can check the default classes.
I needed to deactivate the listener to this event after it was triggered once, because it will also be triggered if I click on another tab link.

Copy
up.on('up:fragment:inserted', function fragmentInsertedCallback() { up.off('up:fragment:inserted', fragmentInsertedCallback) // check if tabLink1 is active, when the compiler starts expect(tabLink1.classList.contains('-active')).toEqual(true) expect(tabLink2.classList.contains('-active')).toEqual(false) }) up.hello(tabNavigation) // triggers the tab navigation compiler tabLink2.click() expect(tabLink1.classList.contains('-active')).toEqual(false) expect(tabLink2.classList.contains('-active')).toEqual(true)

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Avatar
Johanna Schalk
Last edit:
5 months ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Johanna Schalk to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more