Skip to content

Instantly share code, notes, and snippets.

@golampo
Created February 22, 2017 20:06
Show Gist options
  • Save golampo/f45465295f83c9120b364568a67dae3f to your computer and use it in GitHub Desktop.
Save golampo/f45465295f83c9120b364568a67dae3f to your computer and use it in GitHub Desktop.
Lazy Data Request - Mixin
import Ember from 'ember';
// Response container
const LazyResponse = Ember.Object.extend({
isWaiting: true,
isError: false,
value: undefined
});
export default Ember.Mixin.create({
_isLazyEnabled: true, //toggle this disable lazy
_isRouteActive: false,
activate() {
this._isRouteActive = true;
},
deactivate() {
this._isRouteActive = false;
},
lazyRequest(requestAction) {
const lazyResponse = LazyResponse.create();
if (this._isLazyEnabled) {
const lazyPromise = Ember.RSVP.resolve(lazyResponse);
lazyPromise.then(() => {
// Need to investigate best method
// of making request lazy
// For now just doing a 'later' of 2s
Ember.run.later(this, function() {
if (this._isRouteActive) {
requestAction()
.then((model) => {
lazyResponse.setProperties({
isWaiting: false,
value: model
});
})
.catch(() => {
lazyResponse.setProperties({
isWaiting: false,
isError: true
});
});
}
}, 2000);
});
return lazyPromise;
} else {
return requestAction().then((model) => {
lazyResponse.setProperties({
isWaiting: false,
value: model
});
return lazyResponse;
});
}
}
});
import Ember from 'ember';
import LazyRequestMixin from '../mixins/lazy-request';
import { requestCourse } from '../utils/mock-api';
export default Ember.Route.extend(LazyRequestMixin, {
model() {
const course = this.lazyRequest(() => {
return requestCourse();
});
return Ember.RSVP.hash({
course
});
}
});
<br>
<br>
{{#if model.course.isWaiting}}
Waiting for data...
{{else}}
<b>Course Title:</b> {{model.course.value.title}}
{{/if}}
<br>
<br>
{
"version": "0.11.0",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.10.2",
"ember-data": "2.11.0",
"ember-template-compiler": "2.10.2",
"ember-testing": "2.10.2"
},
"addons": {}
}
// mock call to an api endpoint
export const requestCourse = function() {
return new Ember.RSVP.Promise((resolve) => {
resolve({
title: 'Hello Harold'
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment