So I’m teaching myself EmberJS and things are going well. Thanks to questions and answers presented here and here I’m past the initial headaches.
I’m now revisiting the “Components” example on the official EmberJS homepage. The simple code example is presented as such; adjusted for the EmberCLI structure of course:
import Ember from 'ember';
export default Ember.Component.extend({
size: 200,
email: '',
gravatarUrl: Ember.computed('email', 'size', function() {
var email = this.get('email').toLowerCase(),
size = this.get('size');
return 'http://ift.tt/ww139j' + md5(email) + '?s=' + size;
})
});
The problem with this is it attempts to fetch the Gravatar URL on each keypress which is expensive and noise for a a fronted application. Instead I would like to delay the fetch of the data until typing has stopped. Based on the posts I have found here as well as here and here the key seems to be to use debounce
to delay the process. So far so good. So looking at those linked examples and the official EmberJS example I whipped this up; but I’m not too hot about it:
import Ember from 'ember';
export default Ember.Component.extend({
email: '',
size: 200,
delay: 500,
watchEmail: function () {
Ember.run.debounce(this, this.gravatarUrlSetValue, this.get('delay'));
}.observes('email', 'size'),
gravatarUrl: Ember.computed('email', 'size', function () {
Ember.run.debounce(this, this.gravatarUrlSetValue, this.get('delay'));
}),
gravatarUrlSetValue: function() {
var email = this.get('email').toLowerCase();
var size = this.get('size');
this.set('gravatarUrl', 'http://ift.tt/ww139j' + md5(email) + '?s=' + size);
}
});
First and foremost, this works. But it seems odd to me that I have two Ember.run.debounce
calls within two functions. Shouldn’t they be combined in some way? Also, note I am using the suggestion from lame_coder
which replaces this return command:
return 'http://ift.tt/ww139j' + md5(email) + '?s=' + size
With this:
this.set('gravatarUrl', 'http://ift.tt/ww139j' + md5(email) + '?s=' + size);
That too seems messy since am I essentially overwriting a method with a value. I mean this all works, but is this just a kludge that could be handled better? For example, the watchEmail
function is never explicitly called, but seems to be needed if not mainly for the .observes('email', 'size')
aspect. What can be done to clean this up and get it to function as desired with the debounce
logic?
Aucun commentaire:
Enregistrer un commentaire