Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

javascript - 如何合并悬停事件背后的常见行为?(How can I combine the common behavior behind hover events?)

When I wrote a hover event with jquery, there was a common behavior I wanted to do with both mouseenter and mouseleave.

(当我用jquery编写一个悬停事件时,我想对mouseenter和mouseleave都做一个普通的行为。)

$foo.hover(
  function () {
    common_before_process();
    // ...
    common_after_process();
  },
  function () {
    common_before_process();
    // ...
    common_after_process();
  }
);

I have extracted the processing as a function here, but I think that it will be easier to read if these two processes are completely removed from the event handler.

(我在这里将处理过程提取为一个函数,但是我认为,如果将这两个过程从事件处理程序中完全删除,将更易于阅读。)

So the question is, is there a way to concisely describe the common processes extracted by the above functions?

(因此,问题是,是否有一种方法可以简洁地描述上述功能提取的通用过程?)

For example, what I want is the following behavior (an example only):

(例如,我想要的是以下行为(仅一个示例):)

$foo.hoverAfter(common_after_process);
$foo.hoverBefore(common_before_process);

$foo.hover(
  function () {
    // ...
  },
  function () {
    // ...
  }
);
  ask by pepp translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would suggest passing a callback to a common function.

(我建议将回调传递给通用函数。)

Something like:

(就像是:)

function toggleHover (callback) {
  common_before_process();
  callback();
  common_after_process();
}

function methodForHoverOn () {}
function methodForHoverOff () {}

$foo.hover(
  function () {
    toggleHover(methodForHoverOn);
  },
  function () {
    toggleHover(methodForHoverOff);
  }
);

The one method executes the common logic, and also executes the closure passed in, which is variable to whatever you need.

(一种方法执行通用逻辑,还执行传入的闭包,该闭包随您需要而变化。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...