为什么在事件发生之前调用这些事件回调?

时间:2016-07-10 18:47:26

标签: javascript css dom javascript-events addeventlistener

我正在使用Angular和jQuery范围之外的事件监听器,我正在同时探索递归。

在这个例子中,我想为一个类的所有成员添加一个简单的监听器,它在鼠标悬停时为文本着色,并在mouseleave上恢复颜色。

对于按下T按钮的班级中的每个成员,

$scope.buttons = document.getElementsByClassName('buttons');
for (var a = 0; a < $scope.buttons.length; a++) {
    colorButtons($scope.buttons[a], 'open');
};

然后切换

$scope.buttons = document.getElementsByClassName('buttons');
for (var a = 0; a < $scope.buttons.length; a++) {
     colorButtons($scope.buttons[a], 'open');
};

我想调用一个函数,该函数将自身添加为每个元素的事件侦听器或执行所需的着色:

function colorButtons(that, way) {
    switch(way) {
        case('open'):
            that.addEventListener('mouseover', colorButtons(that, null));
            that.addEventListener('mouseleave', colorButtons(that, undefined));
            break;
        case('close'):
            that.removeEventListener('mouseover', colorButtons(that, null));
            that.removeEventListener('mouseleave', colorButtons(that, undefined));
            break;
        case(null):
            $(that).css('color', '#e6ffff');
            break;
        case(undefined):
            $(that).css('color', '#000000');
            break;
        }
}

但是,我发现在初始切换时调用了事件监听器的回调,而不是在悬停/悬停时调用,我想知道原因。

1 个答案:

答案 0 :(得分:0)

好的,所以,解决这个问题的一种方法是首先识别,正如@elclanrs指出的那样,听众期望功能,而不是结果。因此,我们无法将params传递给侦听器回调。

相反,替换params的最佳方法是创建一个缓存对象,即

$scope.buttonCache = { that: {}, way: '' };

并将这些属性替换为params,如下所示:

$scope.buttons = document.getElementsByClassName('buttons');
for (var a = 0; a < $scope.buttons.length; a++) {
    $scope.buttonCache.that = $scope.buttons[a];
    $scope.buttonCache.way = 'open';
    colorButtons();
};

...

$scope.buttons = document.getElementsByClassName('buttons');
for (var a = 0; a < $scope.buttons.length; a++) {
     $scope.buttonCache.that = $scope.buttons[a];
     $scope.buttonCache.way = 'close';
     colorButtons();
};

...

function colorButtons() {
    switch($scope.buttonCache.way) {
        case('open'):
            $scope.buttonCache.way = null;
            $scope.buttonCache.that.addEventListener('mouseover', colorButtons);
            $scope.buttonCache.way = undefined;
            $scope.buttonCache.that.addEventListener('mouseleave', colorButtons);
            break;
        case('close'):
            $scope.buttonCache.way = null;
            $scope.buttonCache.that.removeEventListener('mouseover', colorButtons);
            $scope.buttonCache.way = undefined;
            $scope.buttonCache.that.removeEventListener('mouseleave', colorButtons);
            break;
        case(null):
            $($scope.buttonCache.that).css('color', '#e6ffff');
            break;
        case(undefined):
            $($scope.buttonCache.that).css('color', '#000000');
            break;
    }
}