JSFiddle - React, Tailwind, and code Playground
by asdf
JavaScript
service.subscribe('some-event', () => {console.log('hi')})
this.events['some-event'].fire(); // should call all subscribed callbacks
// services also need to be able to unsubscribe from events
class EventEmitter {
constructor() {
this.count = 0
this.suscribers = {}
}
trigger(event: string, ...params) {
this.subscribers[event].keys().forEach(key => this.subscribers[event][key](...params))
}
listenTo(event: string, fn) {
if (!this.subscribers[event]) {
this.subscribers[event] = {}
}
this.subscribers[event][this.count] = fn
const r = {unsubscribe: () => {
delete this.suscribers[event][this.count]
}}
this.count++
return r
}
/* removeListener(event: string, fn) {
if (!this.subscribers[event]) return
const idx = this.subscribers[event].find(f => {f === fn})
this.subscribers[event].splice(idx, 1)
} */
}
animate(element, px, duration)
function animate(element, px, time) {
element.style.left(0)
const step = time/px
const count = 1
const id = setInterval(() => {
if (count > px) {just post you
clearInterval(id)
return
}
element.style.left(`${count}px`)
count++
}, step)
}
function animate(el, px, time) {
let start = Date.now();
requestAnimationFrame(cb);
function cb() {
const now = Date.now()
if ((now - start) < time) {
el.style.left = (now - start / duration) * px
requestAnimationFrame(cb)
} else {
el.style.left = px
}
}
}
let start = Date.now();
requestAnimationFrame(cb);
function cb() {
timeNow = Date.now()
if ((timeNow - start) < duration) {
el.style.left = (timeNow - start / duration) * px
requestAnimationFrame(cb)
}
}