窗口关闭时的灰烬事件

时间:2015-08-20 20:50:31

标签: javascript ember.js

当用户关闭浏览器时,我希望在窗口关闭之前运行一些代码,因为如果不是,则会导致其他用户出现问题。我正在处理的应用程序的一部分是随机视频聊天。房间由用户创建,当他们等待某人加入时,他们关闭浏览器标签/窗口,然后房间没有正确关闭,仍然可以让其他用户加入。

我见过很多使用beforeunload的例子,但是他们对Ember并不适合我。也许我错过了一种更糟糕的做事方式,或者我可能需要依靠心跳方法?

我一直在尝试做的是使用窗口beforeunload事件,但我没有运气。如果有更好的方法来解决我的上述问题,我全都听见了!

现在我在setupController中绑定方法,例如:

$(window).bind('beforeunload', function() {
  console.log('ending chat');
  this.endChat();
});

我也在路线中试过这段代码,也许在视图中(过去一个月里尝试了很多东西,我不记得所有东西)。

更新:代码更新

这是setupController引用控制器对象而不是窗口。

setupController: function(controller, hash){

    $(window).on('beforeunload', () => {
      controller.hasStarted ? controller.endChat() : controller.send('leaveChat');
    });

    $(window).on('click', () => {
      controller.hasStarted ? controller.endChat() : controller.send('leaveChat');
      console.log('you just clicked');
    });
}

窗口点击事件完全触发,但在beforeunload事件中没有任何反应 - 窗口正常关闭而不触发任何操作/方法。

2 个答案:

答案 0 :(得分:1)

endChat在哪里定义?您当前编写的方式,this.endChat()的范围限定在窗口中。我猜你想把它限制在控制器或路线上。

如果您使用的是Ember CLI,则可以使用胖箭头语法保留在外部范围内,如下所示:

// routes/application.js
import Ember from 'ember';

export default Ember.Route.extend({
  setupController: function () {
    $(window).on('beforeunload', () => {
        this.endChat();
    });
  },

  endChat: function () {
    // do the thing
  }
});

如果没有,那么你可以用老式的方式做到:

App.ApplicationRoute = Ember.Route.extend({
  setupController: function () {
    var _this = this;

    $(window).on('beforeunload', function () {
        _this.endChat();
    });
  },

  endChat: function () {
    // do the thing
  }
});

这有用吗?

答案 1 :(得分:0)

export default Ember.Route.extend({
 setupController: function () {

    Ember.$(window).on('beforeunload', function(e){
        e.returnValue = "hi";
        return e.returnValue;
    });

  }

});