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;
      }
    }
  }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top