JavaScript 将代码添加到已经设置的事件中

JavaScript add code to an already set event

本文关键字:设置 事件 代码 添加 JavaScript      更新时间:2023-09-26

>我尝试将新代码添加到已经设置的事件中,但不知道如何在不再次编写代码的情况下执行此操作?

如您所见,我有一个onComplete事件,该事件在完成Flash文件后抛出alert()。现在我还想打开一个jQuery对话框。我该怎么做?

<html><head><title>testAddEvent</title>
    <script type="text/javascript" src="filesOthersForTesting/jquery-1.x.x.min.js"></script>
    <script type="text/javascript" src="filesFromJWPlayer/jwplayer.js"></script>
    <script type="text/javascript">
        $(function(){
            jwplayer('playerDiv-1').setup({
                flashplayer: 'filesFromJWPlayer/player.swf',
                file: 'sampleContent/bla.flv',
                provider: 'video',
                height: 300,
                width: 300,
                stretching: 'uniform',
                events: {
                    onComplete: function() {
                        alert('Complete!');
                    }
                }
            });
        });
    </script>
<body>
    <div id="playerDiv-1"></div>
</body>
</html>

更新 1:
此代码是一个示例。 alert()是一堆行的示例。一般来说的问题是,我可以向已经初始化的事件添加一些东西吗(events.onComplete)。

像这样:参数events.onComplete = events.onComplete + 'new code here';

@Pointy:是的,jQuery 1.3.2 是旧的,切换到 x ;)。

function decorateBefore(target, decorator) {
    var fn = function () {
        decorator.apply(this, arguments);
        return target.apply(this, arguments);
    };
    // fix inheritance if it's constructor 
    // (it's not needed in your case)
    fn.prototype = target.prototype;
    return fn;
}    
someObj.onComplete = decorateBefore(someObj.onComplete, function(){
  // my code here
  // this function will accept same arguments as original, it's return value will be ignored
})