Skip to content

Instantly share code, notes, and snippets.

@neborn
Last active November 6, 2020 03:37
Show Gist options
  • Save neborn/acc287b3a4eafd17454dbd523d597944 to your computer and use it in GitHub Desktop.
Save neborn/acc287b3a4eafd17454dbd523d597944 to your computer and use it in GitHub Desktop.
TrackedSet Helper
import Controller from '@ember/controller';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { TrackedSet } from 'tracked-built-ins';
export default class ApplicationController extends Controller {
@service
myService;
myThings = new TrackedSet(new Set(['Thing 1', 'Thing 2']));
get cart() {
return this.myService.getInstanceOfCart();
}
@action
newThing(evt) {
this.myThings.add(evt.target.newThing.value);
}
}
import Helper from '@ember/component/helper';
import { inject as service } from '@ember/service';
export default class MyHelper extends Helper {
@service
myService;
get cart() {
return this.myService.getInstanceOfCart();
}
compute([thing]) {
return this.cart.isThingInCart(thing);
}
}
import Service from '@ember/service';
import { TrackedSet } from 'tracked-built-ins';
import { action } from '@ember/object';
class Cart {
_mySet = new TrackedSet();
@action
isThingInCart(thing) {
return this._mySet.has(thing.slice(2));
}
@action
addThingToCart(thing) {
this._mySet.add(thing.slice(2));
}
@action
removeThingFromCart(thing) {
this._mySet.delete(thing.slice(2));
}
}
export default class MyService extends Service {
_cart = new Cart();
@action
getInstanceOfCart() {
return this._cart;
}
}
<form {{on "submit" this.newThing}} action="javascript:void()">
<label for="new-thing">New Thing</label>
<input type="text" id="new-thing" name="newThing">
<button>Add</button>
</form>
<ul>
{{#each this.myThings as |thing|}}
<li>
{{thing}}
{{#if (my-helper thing)}}
<button type="button" {{on "click" (fn this.cart.removeThingFromCart thing)}}>Remove from my class</button>
{{else}}
<button type="button" {{on "click" (fn this.cart.addThingToCart thing)}}>Add to my class</button>
{{/if}}
</li>
{{/each}}
</ul>
{
"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-built-ins": "1.0.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment