当用户关闭浏览器时,我想在窗口关闭之前运行一些代码,否则会给其他用户带来问题。我正在处理的部分应用程序具有随机视频聊天功能。房间是由用户创建的,当他们等待某人加入时,他们关闭了浏览器选项卡/窗口,然后房间没有正确关闭,仍然打开供其他用户加入。
我见过很多使用 beforeunload 的示例,但它们对我来说对 Ember 不起作用。也许我缺少一种更 ember 的做事方式,或者我可能需要依赖心跳方法?
我一直试图做的是使用 window beforeunload 事件,但我一直没有成功。如果有更好的方法来解决我的上述问题,我会洗耳恭听!
现在我在 setupController 中绑定(bind)方法,例如:
$(window).bind('beforeunload', function() {
console.log('ending chat');
this.endChat();
});
我还在路由中尝试过这段代码,也许在 View 中也尝试过(过去一个月尝试了很多事情,我不记得所有事情了)。
更新:代码更新
这里是指 Controller 对象而不是窗口的 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()
的范围限定为窗口。我猜您希望它的范围限定为 Controller 或路由。
如果您使用的是 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
}
});
这样行吗?
关于javascript - 窗口关闭时的 Ember 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32128141/