在一个对象中我定义了一些事件:键是事件名称,值是回调函数。这是一个例子:
vm.events = {
check_node: function(node, selected){
...
},
uncheck_node: function(node, selected){
...
}
};
我想为这些功能添加一些代码,所以我做了以下几点:
for (var evt in scope.tree.events) {
if (scope.tree.events.hasOwnProperty(evt)) {
var cb = scope.tree.events[evt];
scope.tree.events[evt] = function(...args){
cb(...args);
controller.$setDirty();
scope.$evalAsync();
};
scope.tree.view.on(evt.indexOf('.') > 0 ? evt : evt + '.jstree', scope.tree.events[evt]);
}
但是JSHint记录了以下警告:
Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (W083)
我该如何解决这个问题?
答案 0 :(得分:0)
您可以使用箭头功能保持相同的范围:
for (var evt in scope.tree.events) {
if (scope.tree.events.hasOwnProperty(evt)) {
var cb = scope.tree.events[evt];
scope.tree.events[evt] = (...args) => {
cb(...args);
controller.$setDirty();
scope.$evalAsync();
};
scope.tree.view.on(evt.indexOf('.') > 0 ? evt : evt + '.jstree', scope.tree.events[evt]);
}
}
答案 1 :(得分:0)
这就是我解决问题的方法:
var cb = function(oldCb) {
return function() {
var result = oldCb.apply(this, arguments);
controller.$setDirty();
scope.$evalAsync();
return result;
};
};
for (var evt in scope.tree.events) {
if (scope.tree.events.hasOwnProperty(evt)) {
var oldCb = scope.tree.events[evt];
scope.tree.view.on(evt.indexOf('.') > 0 ? evt : evt + '.jstree', cb(oldCb));
}
}