Ember js save data before window unload - ember.js

I want to save user progress, before user leaves a page. What is the best way to do this in Ember.js (v 1.0.0-pre.4)?
In pure JQuery it will look like:
$(window).unload(function() {
ajaxSaveUserProgress();
return true;
});
In Ember I am trying to do something like this:
Exam.TestView = Ember.View.extend({
unload: function(event){
controller.ajaxSaveUserProgress(); // call controller method
console.log('UNLOADED'+get(this, 'controller.test'));
}
});

Personally I'd put this code in the ApplicationRoute, as I believe the ApplicationRoute's setupController is only executed the once when the application is first initialised. You'll have to double-check this, but that's my understanding of it.
I've commented out the code you'll want because I've also demonstrated how the AJAX request needs to be set to synchronous, otherwise the window will close and your AJAX request won't have finished. We naturally need to wait for it to finish before the window is closed.
App.ApplicationRoute = Ember.Route.extend({
setupController: function() {
// var controller = this.controllerFor('foo');
// controller.ajaxSaveUserProgress();
jQuery(window).on('unload', function() {
jQuery.ajax({ type: 'post', async: false, url: 'foo/bar.json' });
});
}
});
Please ignore my jQuery instead of $ (Personal preference!)

Ember's got a standard way of handling this now. From the docs:
App.FormRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
if (this.controller.get('userHasEnteredData') &&
!confirm("Are you sure you want to abandon progress?")) {
transition.abort();
} else {
// Bubble the `willTransition` action so that
// parent routes can decide whether or not to abort.
return true;
}
}
}
});

Related

Ember: How to cleanly replace model data and have progress indicators

I have a certain route that shows a list of projects, and it gets initial data from my RESTAdapter based on who the user is.
I am now implementing a search function that will issue a new API call so the user can get records besides the default ones for them, and the response should replace the model for that route. I have all that working, but I'm not sure how to do a loading or progress indicator (as the response from the database could potentially take 5-10 seconds depending on the amount of data). I know about loading substates, but in this case I'm not transitioning between routes. I just want to have at minimum a spinner so the user knows that it's working on something.
Would anyone that's done this before be willing to share how they handled a)replacing the model with new data, and b)keeping the user informed with a spinner or something?
Form action called when user clicks the Search button
searchProjects: function() {
var query = this.get('queryString');
if (query) {
var _this = this;
var projects = this.store.find('project', {q: query});
projects.then(function(){
_this.set('model', projects);
});
}
}
a) replacing the model with new data
You don't need to do anything. If you sideload records properly from the backend, Ember will automatically update them on the frontend.
b) keeping the user informed with a spinner or something
The loading substate is an eager transition. Ember also supports lazy transitions via the loading event.
You can use that event in order to display the spinner.
Here's an example from the docs:
App.ApplicationRoute = Ember.Route.extend({
actions: {
loading: function(transition, route) {
showSpinner();
this.router.one('didTransition', function() {
hideSpinner();
});
return true; // Bubble the loading event
}
}
});
UPD1
I need to do at least what I'm doing right? Setting the model to the response?
You need to reflect the search in the URL via query params. This will let the router automatically update the model for you.
what I would put in showSpinner to affect stuff on the page (like, can I use jQuery to show or hide a spinner element?), or show the actual loading substate.
I would set a property on that page's controller:
App.IndexRoute = Ember.Route.extend({
queryParams: {
search: {
refreshModel: true
}
},
model () {
return new Ember.RSVP.Promise( resolve => setTimeout(resolve, 1000));
},
actions: {
loading (transition, route) {
this.controller.set('showSpinner', true);
this.router.one('didTransition', () => {
this.controller.set('showSpinner', false);
});
return true;
}
}
});
App.IndexController = Ember.Controller.extend({
queryParams: ['search'],
search: null,
showSpinner: false,
});
Demo: http://emberjs.jsbin.com/poxika/2/edit?html,js,output
Or you could simply put the spinner into the loading template, which will hide obsolete data:
http://emberjs.jsbin.com/poxika/3/edit?html,js,output
Or you could put your spinner into the loading template:
Just in case others want to see, here's my working code based on #lolmaus's answers.
These Docs pages were helpful as well
Route's queryParams and Find method
Controller
//app/controllers/project.js
export default Ember.ArrayController.extend({
queryParams: ['q'],
q: null,
actions: {
searchProjects: function() {
var query = this.get('queryString');
if (query) {
this.set('q', query);
}
}
}
})
Route
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model: function(params) {
if (params.q) {
return this.store.find('project', params);
} else {
return this.store.findAll('project');
}
},
queryParams: {
q: {
refreshModel: true
}
},
actions: {
loading: function(/*transition, route*/) {
var _this = this;
this.controllerFor('projects').set('showSearchSpinner', true);
this.router.one('didTransition', function() {
_this.controllerFor('projects').set('showSearchSpinner', false);
});
return true; // Bubble the loading event
}
}
});
My issue now is that when I use the parameter query, it works great, but then if I clear the query (with an action, to effectively "go back") then the records fetched by the query stay in the store, so when it does a findAll() I have both sets of records, which is not at all what I want. How do I clear out the store before doing findAll again?

Ember Select component rendering before promise is resolved

I have a component which adds some functionality to a <select> tag. I want to initialise some javascript after the <select> has fully rendered including all <option> tags. The data used to populate the <option> tags is an array of objects provided from an ajax request.
I'm using ember-data and finding this works when the data is provided from the store, meaning it is an instance of DS.RecordArray which has helpful properties like isLoaded. However, when the data is provided from a jQuery ajax call and is just plain JSON, it appears as though the component tries to render everything before the promise returned by jQuery is fulfilled.
I feel the issue is with how I'm handling promises as the issue seems to be related to things initialising before they should (ie promises have resolved properly). I tried wrapping the ajax call in an RSVP.Promise object but not luck, (I'm using Ember-CLI). Below is a simplified version of what I have so far. Any help would be appreciated.
// My route
export default Ember.Route.extend({
setupController: function(controller, model) {
this._super(controller, model);
var hash = Ember.RSVP.hash({
// myOptions: $.getJSON('/api/options')
myOptions: new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: '/api/options',
type: 'get',
dataType: 'json',
success: function(result) {
Ember.run(null, resolve, result);
},
error: function(result) {
Ember.run(null, reject, result);
}
});
})
});
return hash.then(function(result) {
controller.set('optionsForSelect', result.myOptions);
});
}
});
// My component
export default Ember.Select.extend({
didInsertElement: function() {
// Is called before ajax request has finished
this.$().mySelectPlugin({
});
}
});
// Handlebars template
{{my-select-plugin content=optionsForSelect optionValuPath="content.id" optionLabelPath="content.name"}}
To me, this seems like something that should be handled in the controller, not the route. Here's what I did for a similar situation.
App.LessonsShowIndexController = Ember.ObjectController.extend({
author: function() {
return this.get('model').get('author');
}.property('author'),
fullName: function() {
return this.get('author').get('firstName') + ' ' + this.get('author').get('lastName');
}.property('author.isFulfilled'),
});
Using the isFulfilled property allows the controller to wait for the promise to resolve before using the data. In your case, you could have a property that returns a promise and another that waits for it to be fulfilled.

Emberjs call a method from an other object

This might be a silly question, but I can't find out anything about it anywhere...
I create a method in one of my controller to verify if the user session is still good, and I'm using this method in almost every page of my app in my beforeModel. But the thing is that I don't want to copy/paste the code every time in every route, this will be dirty and I really don't like it.
Lets say I have this controller :
App.LoginController = Ember.ObjectController.extend({
...
isSession: function() {
var session = this;
Ember.$
.get(host + '/session', function(data) {
console.log('DEBUG: Session OK');
})
.fail(function() {
console.log('DEBUG: Session FAIL');
session.transitionToRoute('login');
});
}
});
How can I call it in this router :
App.HomeRoute = Ember.Route.extend({
beforeModel: function(transition) {
//Here
},
model: function() {
return this.store.all('login');
}
});
I've tried this this.get('loginController').isSession(); but I receive this error Error while loading route: TypeError: Cannot call method 'isSession' of undefined
Thanks for the help !
[edit]
I don't have much to show but this :
My map
App.Router.map(function() {
this.route('login', { path: '/' });
this.route('home');
this.resource('enquiries', function() {
this.route('enquiry', { path: '/:enquiry_id' }, function() {
this.route('update');
});
});
});
Most likely I only Have a LoginController and my HomeRoute. (its the beginning of the app)
I don't need to create a Route for my Login because I have an action helper in my login template and I'm redirected to my Home template after that.
You need to use controllerFor() method in order to call method on controller from router. If method is an action you need to use send() method, like this.controllerFor('login').send('isSession')
App.HomeRoute = Ember.Route.extend({
actions: {
willTransition: function(transition) {
transition.abort();
this.controllerFor('login').isSession()
}
});
If you don't need a return value from isSession you might consider making it an action on a top-level route. The router.send method in the docs has a pretty good example of how you declare actions as well as how you call them. Note that send is also a method you can call on a controller. Actions bubble up from a controller, to the parent route, and then all the way up the route hierarchy, as shown here

Obversing route change to apply equivalent to onload

I'm trying to observe the route change to apply some common action once rendered. The idea is to have a feature similar to the onload but as we use a single-page app this needs to be triggered on each route changes. (could be scoped to the new view)
I found how to observe the currentPath changes:
App.ApplicationController = Ember.Controller.extend({
currentPathDidChange: function() {
prettyPrint()
}.observes('currentPath');
});
While this works good in some cases, it gets triggered when the route changes, but still to early to apply content changes as it seem to append before the content gets rendered.
Any idea on the best practice to achieve such goal?
Have you tried deferring the code with Ember.run.schedule? For instance,
App.ApplicationController = Ember.Controller.extend({
currentPathDidChange: function() {
Ember.run.schedule('afterRender', this, function() {
prettyPrint();
});
}.observes('currentPath')
});
Due to the deprecation of Controllers in Ember 1.x finding the url in the router would be a good way to future proof your apps. You can do this in ember-cli like so:
// similar to onLoad event behavior
export default Ember.Route.extend({
afterModel: function (model){
Ember.run.next(() => {
console.log(this.get('router.url'));
});
}
});
// hacky way to get current url on each transition
export default Ember.Route.extend({
actions: {
didTransition: function() {
Ember.run.next(() => {
console.log(this.get('router.url'));
});
}
}
});
This will log: /posts and /posts/3/comments ect.

Emberjs scroll to top when changing view

When the main view of my application is switched (new route that reconnects the main outlet of my application controller) I want the page to be scrolled to the top. Otherwise it's a bit strange that I navigate to another page-like view and the viewport is still lost somewhere where I left off.
I hacked a solution and wonder if there's a better way or if anyone has the same thing.
Here's what I do:
App.ApplicationController = Ember.Controller.extend({
connectOutlet: function(){
window.scrollTo(0, 0);
this._super.apply(this, arguments);
}
});
#Baruch's solution is good, but when I implemented it I had render on elements within my application state and would cause a scrollTop when it was not needed.
I found this to be much more effective as it only runs on the path change:
App.ApplicationController = Ember.Controller.extend({
currentPathChanged: function () {
window.scrollTo(0, 0);
}.observes('currentPath')
});
I achieved this with the following code:
Ember.Route.reopen({
render: function(controller, model) {
this._super();
window.scrollTo(0, 0);
}
});
Coffee Script:
Ember.Route.reopen
activate: ->
#_super()
window.scrollTo(0, 0)
Javascript:
Ember.Route.reopen({
activate: function() {
this._super();
window.scrollTo(0, 0);
}
});
You should probably try and extend Ember.Route and add your window.scrollTo in the enter callback. Then instead of using Ember's Route for your leaf routes, you call your route .extend(), so they'll automatically scroll up when you enter a route/state. Something similar to this:
// define your custom route and extend "enter"
var MyRoute = Em.Route.extend({
enter: function(router) {
// for now on, all the routes that extend this,
// will fire the code in this block every time
// the application enters this state
// do whatever you need to do here: scroll and whatnot
}
});
App.Router = Em.Router.extend({
enableLogging: true,
location: 'hash',
index: Em.Route.extend({
route: '/',
connectOutlets: function(router) {
...
},
// on your leaf routes, use your own custom route that
// does your scroll thing or whatever you need to do
home: MyRoute.extend({
route: '/',
connectOutlets: function (router, context) {
...
}
}),
// other routes...
})
});
does it make sense?
It's now render(name, options), and if you are specifically calling render (ie with a modal) you want to pass that to super()
Ember.Route.reopen({
render: function(name, options) {
if (name != null) {
return this._super(name, options);
} else {
return this._super();
}
}
});
Ember 3.12+ (this is technically 3.20 code listed here)
import EmberRouter from '#ember/routing/router';
const Router = EmberRouter.extend({
init() {
// call event everytime route changes
this.on('routeDidChange', () => {
this._super(...arguments);
window.scrollTo(0, 0); // scrolls to top
});
}
});
Router.map(function () {
// your mapping code goes here
});
export default Router;
Prior to 3.12 (this is technically 3.4 but the key code should be the same)
import EmberRouter from '#ember/routing/router';
const Router = EmberRouter.extend({
didTransition() {
this._super(...arguments);
window.scrollTo(0, 0);
}
});
Router.map(function () {
// your mapping code goes here
});
export default Router;
We have handled this problem serveral times and the way we've found that is the easiest and most straight-forward way is to configure this once in the router.js file using a 'route transition' event function. We used didTransition before it got deprecated in Ember 3.12 in lieu of routeDidChange. I've posted both examples below. Some syntax may differ slightly depending on which version of Ember you are on but this core code should be the same.