@PelagicCreatures/sargasso
Defining Sargasso subclasses
This subclass listens for clicks on the element so we need to:
- override the start() method to add a click handler to the element
- ovveride the sleep() method to remove the click handler
Don't forget to call super.start() at the top of start and super.sleep() on the tail of sleep.
Notice the use of animation frames to make DOM changes - this leads to cleaner screen updates.
Sargasso will take care of the rest.
Example:
HTML
<button class="mdc-button mdc-button--raised mdc-ripple-upgraded">
<div class="mdc-button__ripple"></div>
<i class="material-icons mdc-button__icon" aria-hidden="true">favorite</i>
<span class="mdc-button__label">Click Me</span>
</button>
(This example uses a Material Design button from @PelagicCreatures/tropicbird but a regular button would work too)
ES
class MyButtonClass extends Sargasso {
start () {
super.start() // important!
// listen for click
this.clicker = (e) => {
this.clicked()
}
this.element.addEventListener('click', this.clicker, false)
}
sleep () {
// cleanup listener
this.element.removeEventListener('click', this.clicker)
super.sleep() // important!
}
clicked () {
// use an animation frame to mutate the DOM
const frame = () => {
if (this.hasClass('clicked')) {
this.removeClass('clicked')
this.element.getElementsByClassName('mdc-button__label')[0].textContent = 'Again!'
} else {
this.addClass('clicked')
this.element.getElementsByClassName('mdc-button__label')[0].textContent = 'Clicked!'
}
}
this.queueFrame(frame) // schedule it
}
}
registerSargassoClass('MyButtonClass', MyButtonClass)