Javascript 窗口关闭时的余烬事件
当用户关闭浏览器时,我想在窗口关闭之前运行一些代码,因为如果不关闭,会给其他用户带来问题。我正在使用的部分应用程序有一个随机视频聊天。文件室是由用户创建的,当用户等待其他用户加入时,他们会关闭浏览器选项卡/窗口,然后文件室未正确关闭,仍然打开供其他用户加入 我见过许多使用beforeunload的示例,但它们不适合我使用Ember。也许我错过了一种更为灰烬的做事方式,或者也许我需要依靠心跳的方法 我一直想做的是在卸载事件之前使用窗口,但我一直没有任何运气。如果有更好的办法来解决我的上述问题,我洗耳恭听 现在,我在setupController中绑定该方法,例如:Javascript 窗口关闭时的余烬事件,javascript,ember.js,Javascript,Ember.js,当用户关闭浏览器时,我想在窗口关闭之前运行一些代码,因为如果不关闭,会给其他用户带来问题。我正在使用的部分应用程序有一个随机视频聊天。文件室是由用户创建的,当用户等待其他用户加入时,他们会关闭浏览器选项卡/窗口,然后文件室未正确关闭,仍然打开供其他用户加入 我见过许多使用beforeunload的示例,但它们不适合我使用Ember。也许我错过了一种更为灰烬的做事方式,或者也许我需要依靠心跳的方法 我一直想做的是在卸载事件之前使用窗口,但我一直没有任何运气。如果有更好的办法来解决我的上述问题,我洗
$(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事件没有发生任何事情-窗口只是正常关闭,没有触发任何操作/方法。哪里定义了
endChat
?您当前编写它的方式,this.endChat()
的作用域是窗口。我猜你希望它的作用域是控制器或路由
如果您使用的是Ember CLI,则可以使用fat arrow语法保留在外部范围内,如下所示:
// 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
}
});
这样行吗
export default Ember.Route.extend({
setupController: function () {
Ember.$(window).on('beforeunload', function(e){
e.returnValue = "hi";
return e.returnValue;
});
}
})) 快到了!是的,事件在控制器上。我已更改它,但无法对beforeunload事件执行任何操作。我在窗口单击事件中添加了另一个事件,以验证所有内容都正确连接,并且正常工作。但在卸载之前,仍然没有任何内容