我刚刚编写了这个服务来提醒用户在关闭窗口时他们是未保存的数据:
module.factory('autosaver',
['$rootScope', '$window', 'editor', 'doc', 'saveInterval', '$timeout',
function ($rootScope, $window, editor, doc, saveInterval, $timeout) {
var scope = $rootScope.$new(true);
scope.doc = doc;
scope.confirmOnLeave = function(e) {
var msg = "You have unsaved data.";
// For IE and Firefox
e = e || window.event;
if (e) {e.returnValue = msg;}
// For Chrome and Safari
return msg;
};
scope.$watch('doc.dirty', function (newValue, oldValue) {
if(newValue !== oldValue) {
newValue ? $window.addEventListener('beforeunload', scope.confirmOnLeave) : $window.removeEventListener('beforeunload', scope.confirmOnLeave);
}
});
return scope;
}]);
现在我想写规范。我不知道如何模拟 beforeunload 事件并监视调用。我试过这段代码:
it('should listen to beforeunload event', inject(function ($window, autosaver) {
autosaver.confirmOnLeave = jasmine.createSpy('confirmOnLeave');
var evt = document.createEvent("beforeunloadEvents");
evt.initMouseEvent("beforeunload", true, true, $window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
$window.dispatchEvent(evt);
}));
但我得到这个错误:
NotSupportedError: NotSupportedError: DOM Exception 9
Error: The implementation did not support the requested type of object or operation.
谢谢你的帮助。