首页 > 解决方案 > jPlayer with playlist: 'ended' 仅在下一曲目的 'setmedia' 之后触发

问题描述

注意:这是一个知识共享问题,因为我已经找到了一个很好的解决方案。

问题:

播放列表实现 ( http://jplayer.org/latest/demo-02-jPlayerPlaylist/ ) 是通过利用 jPlayer 事件构建的。这样做的一个副作用是,如果你想通过绑定到'setmedia'来响应track start,并通过绑定到'ended'事件来响应track end,你会发现'ended'只有在下一行之后才会触发被激活。

这意味着事件将按以下顺序触发:

所以问题是:如何在移动到下一个轨道之前触发“结束”事件?

标签: jplayer

解决方案


这个问题的根本原因是播放列表实现在我们的绑定之前将自己绑定到了“结束”事件

所以解决方案是在播放列表的代码之前绑定我们的代码。

在以下答案中:jQuery bind event listener before another我们可以找到 preBind 方法的以下实现:

$.fn.preBind = function (type, data, fn) {
    this.each(function () {
        var $this = $(this);

        $this.bind(type, data, fn);

        var currentBindings = $._data(this, 'events')[type];
        if ($.isArray(currentBindings)) {
            currentBindings.unshift(currentBindings.pop());
        }
    });
    return this;
};  

添加此 preBind 后,我们可以在 jPlayer 'ready' 处理程序中执行以下操作:

$("#jquery_jplayer_1")
    .preBind($.jPlayer.event.ended, function(e) { 
        var cur = $('.jp-playlist').find('li.jp-playlist-current'),
            ix = cur.index(),
            is_last = cur.next().get().length == 0;
        console.log('ended index=' + ix + ', is_last=' + is_last);
    });   

推荐阅读