Skip to content

Instantly share code, notes, and snippets.

@MichalBryxi
Forked from fhrbek/controllers.application.js
Last active April 4, 2017 10:14
Show Gist options
  • Save MichalBryxi/527f4bee3de524aea13f83d0b70b789a to your computer and use it in GitHub Desktop.
Save MichalBryxi/527f4bee3de524aea13f83d0b70b789a to your computer and use it in GitHub Desktop.
Slow response + data proxy
import Ember from 'ember';
export default Ember.Controller.extend({
appName: 'Randomly Slow Route Demo with bypassing setupController'
});
import Ember from 'ember';
export default Ember.Controller.extend({
});
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: 'none',
rootURL: config.rootURL
});
Router.map(function() {
this.route('slow-route', {path: '/'});
});
export default Router;
import Ember from 'ember';
const API = [
{
data: [1, 2, 3],
responseTime: 100
}, {
data: [100, 200, 300],
responseTime: 1000
}, {
data: [1000, 2000, 3000],
responseTime: 500
}];
const jobListDataTemplate = Ember.Object.extend({
jobs: null,
totalJobCount: 0,
currentPage: 1,
isLoading: true,
orderBy: [{field: 'timestamp', order: 'desc'}],
lastLoadRequest: 0,
totalPages: Ember.computed('totalJobCount', function () {
return Math.ceil(this.get('totalJobCount') / RECORDS_PER_PAGE);
}).readOnly()
});
export default Ember.Route.extend({
dataVersion: 0,
jobListData: Ember.computed(function () { return jobListDataTemplate.create(); }),
_fetchData: function () {
let controller = this.controllerFor('slow-route');
let dataVersion = this.get('dataVersion');
console.log('REFRESH DATA WITH VERSION', dataVersion, ' (IT WILL TAKE', API[dataVersion].responseTime, 'ms)');
Ember.run.later(function () {
let data = API[dataVersion].data;
console.log('DATA VERSION', dataVersion, 'RETRIEVED: ', data);
controller.set('model', data);
}, API[dataVersion].responseTime);
},
_loadPage(page, requestedOrderField, requestedOrderDirection) {
const jobListData = this.get('jobListData'),
// increment the request when the request is made. Only the most recent request will be honored.
requestNumber = this.incrementProperty('jobListData.lastLoadRequest');
const queryParams = {
orderBy: requestedOrderField,
order: requestedOrderDirection,
offset: (page - 1) * RECORDS_PER_PAGE,
limit: RECORDS_PER_PAGE
};
this.store.query('jobs/job', queryParams).then((jobs) => {
// if the load numbers don't match, we shouldn't use this request because another was made.
if (requestNumber === this.get('jobListData.lastLoadRequest')) {
const meta = jobs.get('meta');
jobListData.setProperties({
jobs: jobs,
totalJobCount: meta.total,
currentPage: page,
orderBy: [{field: requestedOrderField, order: requestedOrderDirection}],
isLoading: false
});
if (!Ember.testing) {
this.backgroundReload(page, requestedOrderField, requestedOrderDirection);
}
}
}, (err) => {
console.log('Request failed');
jobListData.set('isLoading', false);
});
},
backgroundReload: function (page, field, order) {
this.set('lastTimer', Ember.run.later(this, '_loadPage', page, field, order, POLLING_FREQUENCY_MS));
},
cancelBackgroundReload: function () {
let timer = this.get('lastTimer');
if (timer) {
Ember.run.cancel(timer);
this.set('lastTimer', null);
}
},
model() {
const jobListData = this.get('jobListData');
jobListData.setProperties({
jobs: null,
totalJobCount: 0,
currentPage: 1
});
jobListData.set('isLoading', true);
this._loadPage(1, orderByValue.field, orderByValue.order);
return jobListData;
},
setupController(controller, model) {
console.log('SETUP CONTROLLER WITH DATA', model);
this._super(controller, model);
},
actions: {
refresh() {
this.set('dataVersion', 1);
this.refresh();
Ember.run.later(() => {
this.set('dataVersion', 2);
this.refresh();
}, 100);
}
}
});
<h1>Welcome to {{appName}}</h1>
<br>
<div>This demo shows how Ember handles (properly) data retrieval concurrency. Here's what you can do:</div>
<ul>
<li>Load the page - you should see items 1, 2, 3</li>
<li>Open browser console (in developer tools) to see debugging messages</li>
<li>Click the Refresh button - you should see items 1000, 2000, 3000 even though obsolete items 100, 200, 300 are retrieved later</li>
<li>Check the console - you should see that after obsolete data retrieval setupController is not called (which is correct)</li>
</ul>
<br>
{{outlet}}
<br>
<br>
<button class="refresher" {{action "refresh"}}>Refresh</button>
<hr>
<div>
<span>Items:</span>
<ul>
{{#each content as |item i|}}
<li class="item-{{i}}">{{item}}</li>
{{/each}}
</ul>
</div>
import { test } from 'qunit';
import moduleForAcceptance from '../../tests/helpers/module-for-acceptance';
moduleForAcceptance('TODO: put something here');
test('visiting /', function(assert) {
visit('/');
andThen(function() {
assert.equal(currentURL(), '/');
});
click('.refresher');
andThen(function () {
assert.equal(find('.item-0').text(), '1000', 'First element has correct value');
});
});
import Ember from 'ember';
export default function destroyApp(application) {
Ember.run(application, 'destroy');
}
import { module } from 'qunit';
import Ember from 'ember';
import startApp from '../helpers/start-app';
import destroyApp from '../helpers/destroy-app';
const { RSVP: { Promise } } = Ember;
export default function(name, options = {}) {
module(name, {
beforeEach() {
this.application = startApp();
if (options.beforeEach) {
return options.beforeEach.apply(this, arguments);
}
},
afterEach() {
let afterEach = options.afterEach && options.afterEach.apply(this, arguments);
return Promise.resolve(afterEach).then(() => destroyApp(this.application));
}
});
}
import Resolver from '../../resolver';
import config from '../../config/environment';
const resolver = Resolver.create();
resolver.namespace = {
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix
};
export default resolver;
import Ember from 'ember';
import Application from '../../app';
import config from '../../config/environment';
const { run } = Ember;
const assign = Ember.assign || Ember.merge;
export default function startApp(attrs) {
let application;
let attributes = assign({rootElement: "#test-root"}, config.APP);
attributes = assign(attributes, attrs); // use defaults, but you can override;
run(() => {
application = Application.create(attributes);
application.setupForTesting();
application.injectTestHelpers();
});
return application;
}
import resolver from './helpers/resolver';
import {
setResolver
} from 'ember-qunit';
setResolver(resolver);
{
"version": "0.12.1",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": true
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.12.0",
"ember-template-compiler": "2.12.0",
"ember-testing": "2.12.0"
},
"addons": {
"ember-data": "2.12.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment