Skip to content

Instantly share code, notes, and snippets.

@jelhan
Forked from lifeart/controllers.application\.js
Created November 26, 2021 16:21
Show Gist options
  • Save jelhan/3472c57f04a6fb4e23b866ebce05ac67 to your computer and use it in GitHub Desktop.
Save jelhan/3472c57f04a6fb4e23b866ebce05ac67 to your computer and use it in GitHub Desktop.
Tracked Observers
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { cached } from 'tracked-toolbox';
import { scheduleOnce } from '@ember/runloop';
const Observers = [];
class Observer {
tags = [];
cb = null;
constructor(tags, cb) {
this.tags = tags();
this.cb = cb;
}
@cached
get value() {
this.tags.forEach(t => t());
return this.cb();
}
}
function addObserver(tags, cb) {
Observers.push(new Observer(tags, cb));
}
function addEffect(cb, deps) {
Observers.push(new Observer(() => deps, cb));
}
function watchTag(context, key) {
return function() {
context[key];
}
}
function consumeObservers() {
for (let observer of Observers) {
observer.value;
}
loop();
}
function loop() {
requestIdleCallback(() => {
scheduleOnce('actions', consumeObservers);
}, { timeout: 100 });
}
loop();
export default class ApplicationController extends Controller {
@tracked time = Date.now();
@tracked msg = '';
get appName() {
return new Date(this.time).toISOString();
}
constructor() {
super(...arguments);
setInterval(() => {
this.time = Date.now();
}, 5000);
let observerCall = 0;
addObserver(() => [watchTag(this, 'time')], () => {
this.msg = `Observer called ${observerCall++} times`;
});
addEffect(() => {
console.log('im side-effect');
}, [watchTag(this, 'time')]);
}
}
<h1>Welcome to {{this.appName}}</h1>
<br>
<br>
{{outlet}}
<br>
<br>
{{this.msg}}
{
"version": "0.17.1",
"EmberENV": {
"FEATURES": {},
"_TEMPLATE_ONLY_GLIMMER_COMPONENTS": false,
"_APPLICATION_TEMPLATE_WRAPPER": true,
"_JQUERY_INTEGRATION": true
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js",
"ember": "3.18.1",
"ember-template-compiler": "3.18.1",
"ember-testing": "3.18.1"
},
"addons": {
"@glimmer/component": "1.0.0",
"tracked-toolbox": "1.2.3"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment