[英]Wrap backbone view events handlers or jQuery event handlers in try catch block
我想对报告JavaScript错误进行全局事件处理。 我们已经在生产中缩小了JS文件,因此我尝试在Sourcemap的帮助下完成它。
不幸的是,未捕获的错误(由浏览器的顶级错误处理程序window.onerror报告)当前在任何当前浏览器中均不包括列号。 HTML5规范已更新为要求这样做,因此在不久的将来可能会更改。
来源: https : //rollbar.com/docs/guides_sourcemaps/
所以现在我需要在try catch块中包装主干视图事件。 应该有扩展Backbone.View的通用方法。 可能在delegateEvents
函数的某个地方。
最后,这是我将所有jQuery事件处理程序包装在try-catch块中的方式。
// 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 && arguments[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.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.