[英]Adding code to an existing function inside loop
In an object I have defined some events: the key is the event name and the value is the callback function. 在一个对象中,我定义了一些事件:键是事件名称,值是回调函数。 Here is an exemple: 这是一个例子:
vm.events = {
check_node: function(node, selected){
...
},
uncheck_node: function(node, selected){
...
}
};
I want to add some code to those functions so I did the following: 我想向这些功能添加一些代码,所以我做了以下工作:
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]);
}
But JSHint logs the following warning: 但是JSHint会记录以下警告:
Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (W083)
How can I solve this ? 我该如何解决?
You could use a arrow function to stay in the same scope: 您可以使用箭头功能保持在同一范围内:
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]);
}
}
This is how I solved my issue: 这是我解决问题的方法:
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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.