我想编写一个适用于特定的基于 JS 的聊天应用程序的 Chrome 扩展程序。每次聊天收到消息时都需要意识到这一点。
现在,我显然可以通过设置计时器并检查 $("chat-messages").childElements().length
是否增加来轻松做到这一点,但我宁愿采用更优雅的方法,设置某种事件处理程序,以便在每次调用 appendChatMessage()
时触发。有办法做到这一点吗?
var oldfunc = appendChatMessage;
appendChatMessage = function() { eval(oldfunc); myChatMessageReceivedHandler(); }
似乎不起作用。
最佳答案
如果有一个方法 appendChatMessage
每次有新消息到达时都会调用,您可以这样做
var old = appendChatMessage;
appendChatMessage = function() {
// call the initial method and store the result
var result = old.apply( this, arguments );
// do your stuff here
// return the initial result
return result;
};
关于javascript - 在任意 JS 函数上设置事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6565796/