【问题标题】:jQuery - on custom event completejQuery - 自定义事件完成
【发布时间】:2015-10-02 09:39:46
【问题描述】:

我创建了一个自定义灯箱插件,我需要在操作异步完成时创建一个自定义事件/侦听器。 我的目标是在我关闭灯箱或转到下一个/上一个项目时销毁/取消设置视频/iframe 源,以防止错误(特别是在 IE 上)。

例如我已经创建了这个脚本:

$.Lightbox = function() {

    var el;

    function init() {
        /*** do some stuff ***/
        getMedia(el);
    }

    function getMedia(el) {
        media_type = 'video';
        switch(media_type) {
            case 'image':
                /*** do some stuff ***/
                load_image();
                break;
            case 'video':
                /*** do some stuff ***/
                load_video();
                break;
        }
    }

    function load_video() {
        el.on('removeVideo',function() {
            /*** do some stuff ***/
        });
    }

    function load_image() {
        el.on('removeVideo',function() {
            /*** do some stuff ***/
        });
    }

    /*** need to be an event that I can trigger and detect when it's finish ***/
    function removeVideo() {
        /*** just for the example ***/
        if ($('iframe').length > 0) {
            $('iframe').attr('src','').load(function(){
                $('iframe').remove();
            });
        } else {
            $('img').remove();
        }
    }

    $(document).on('click touchend',next_prev, function() {
        el.on('removeVideo',function() {
            getMedia();
        });
        return false;
    });

    $(document).on('click touchend',close, function() {
        el.on('removeVideo',function() {
            /*** do some stuff ***/
        });
        return false;
    });

    init();

};

在插件中创建自定义事件监听器的正确方法是什么。我不知道如何处理它以及创建它的正确方法是什么。

【问题讨论】:

    标签: jquery events plugins listener


    【解决方案1】:

    参见 .bind() 和 .trigger() 方法:

    http://api.jquery.com/bind/

    http://api.jquery.com/trigger/

    el.bind("removeVideo", function() {
      // what to do when removeVideo is triggered
    });
    

    那么你就可以触发事件了:

    el.trigger("removeVideo");
    

    编辑:

    removeVideo完成后执行代码

    解决方案 1:

    function removeVideo() {
        ...
        el.trigger("removeVideoComplete");
    }
    
    el.bind("removeVideoComplete", function() {
        // What you want
    });
    

    解决方案 2:

    function removeVideo() {
        ...
        // simply do what you want ! Maybe call a function ? 
    }
    

    解决方案 3:

    function removeVideo(callback) {
        ...
        callback(el);
    }
    
    ...
    var callback = function(el) {
        // what you want
    }
    removeVideo(callback);
    

    【讨论】:

    • 感谢您的回答。但是这种原理似乎是同步的,我需要一些等待异步任务完成的东西,比如 .load()。可能的目标是仅在 removeVideo 完成时执行代码。你的方法不是这样的......
    猜你喜欢
    • 2012-11-05
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 2017-05-31
    • 2019-11-12
    • 2011-12-05
    相关资源
    最近更新 更多