gpt4 book ai didi

javascript - 将主干 View 事件处理程序或 jQuery 事件处理程序包装在 try catch block 中

转载 作者:行者123 更新时间:2023-11-28 08:28:50 25 4
gpt4 key购买 nike

我想要进行全局事件处理来报告 JavaScript 错误。我们在生产环境中缩小了 JS 文件,因此我尝试在 Sourcemap 的帮助下完成它。

Unfortunately, uncaught errors (reported by the browser's top-level error handler, window.onerror) do not currently include column numbers in any current browser. The HTML5 Spec has been updated to require this, so this may change in the near future.
Source : https://rollbar.com/docs/guides_sourcemaps/

所以现在我需要将主干 View 事件包装在 try catch block 中。应该有扩展 Backbone.View 的通用方法。可能在 delegateEvents 函数的某个地方。

最佳答案

下面是我最终将所有 jQuery 事件处理程序包装在 try-catch block 中的方法。

// maintain a reference to the existing function
var oldOn = $.fn.on;
// ...before overwriting the jQuery extension point
$.fn.on = function(types, selector, data, fn, /*INTERNAL*/ one) {
// parameter correction for backward compatibility copied from `on` function of jQuery JavaScript Library v1.9.0

// Types can be a map of types/handlers
if (typeof types === "object") {
// ( types-Object, selector, data )
if (typeof selector !== "string") {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for (type in types) {
this.on(type, selector, data, types[type], one);
}
return this;
}

if (data == null && fn == null) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if (fn == null) {
if (typeof selector === "string") {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if (fn === false) {
fn = returnFalse;
} else if (!fn) {
return this;
}
// ENDS - parameter correction for backward compatibility copied from `on` function of jQuery JavaScript Library v1.9.0

if (fn) {
var origFn = fn;
var wrappedFn = function() {
try {
origFn.apply(this, arguments);
} catch (e) {
//handle the error here.
}
};
fn = wrappedFn;
}
return oldOn.apply(this, [types, selector, data, fn, /*INTERNAL*/ one]);
};


更新:

有一个错误,jQuery-UI 可放置的 div 像胶水一样粘在鼠标指针上,而不是被丢弃,并且它被追踪到这个代码作为罪魁祸首。

因此,请确保使用条件 if(!(arguments.length === 4 && argument[1] === null)) {}

包装此扩展

像这样。

// maintain a reference to the existing function
var oldOn = $.fn.on;
// ...before overwriting the jQuery extension point
$.fn.on = function(types, selector, data, fn, /*INTERNAL*/ one) {

// We can ignore .bind() calls - they are passed from jquery-ui or other outdated components
if(!(arguments.length === 4 && arguments[1] === null)) {
//rest of the above code here.
}
}

关于javascript - 将主干 View 事件处理程序或 jQuery 事件处理程序包装在 try catch block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22087601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com