Skip to content

Instantly share code, notes, and snippets.

@k-fish
Last active December 6, 2019 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k-fish/0e05df2381ca8cd6b7bd7a70fd672877 to your computer and use it in GitHub Desktop.
Save k-fish/0e05df2381ca8cd6b7bd7a70fd672877 to your computer and use it in GitHub Desktop.
Debounce Example
import Ember from 'ember';
import { run } from '@ember/runloop';
const DEBOUNCE_TIME = 200;
export default Ember.Component.extend({
functionCallCount: 0,
_internalFunction() {
this.set('functionCallCount', this.functionCallCount + 1);
},
fireMyAction(named) {
if (named) {
run.debounce(this, this._internalFunction, DEBOUNCE_TIME);
} else {
run.debounce(this, () => {
this.set('functionCallCount', this.functionCallCount + 1);
}, DEBOUNCE_TIME);
}
},
actions: {
clickNamed() {
for (let i = 0; i < 10; i++) {
this.fireMyAction(true);
}
},
clickAnonymous() {
for (let i = 0; i < 10; i++) {
this.fireMyAction(false);
}
}
}
});
{{example-component
}}
<div style="background-color:hsl(140,50%,50%); padding: 20px; border-radius: 5px; cursor: pointer; display: flex; margin: 10px; flex-direction: column; align-items: center" {{action 'clickNamed'}} >
<span>Debounced with <strong>named</strong> function</span>
Click here to fire action 10 times
</div>
<div style="background-color:hsl(180,50%,50%); padding: 20px; border-radius: 5px; cursor: pointer; display: flex; margin: 10px; flex-direction: column; align-items: center" {{action 'clickAnonymous'}} >
<span>Debounced with <strong>anonymous</strong> function</span>
Click here to fire action 10 times
</div>
<div style="margin:10px;">
Action has been fired <strong>{{functionCallCount}}</strong> times
</div>
{
"version": "0.15.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js",
"ember": "3.4.3",
"ember-template-compiler": "3.4.3",
"ember-testing": "3.4.3"
},
"addons": {
"ember-data": "3.4.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment