Javascript Spotify更改:上下文事件
我有以下代码:Javascript Spotify更改:上下文事件,javascript,spotify,spotify-app,Javascript,Spotify,Spotify App,我有以下代码: function initializeUI(){ //More code here models.player.addEventListener('change:context', contextChanged); //More code here } var timerId = null; function contextChanged() { models.player.load('context').done(function (pla
function initializeUI(){
//More code here
models.player.addEventListener('change:context', contextChanged);
//More code here
}
var timerId = null;
function contextChanged() {
models.player.load('context').done(function (player) {
if (player.context.uri == tempPlaylist.uri) {
//User started playing this context. Start timer.
timerId = setInterval(updateTimerView, 1000);
}
else {
//User is playing a different context. Delete temp playlist and timer.
models.Playlist.removeTemporary(tempPlaylist);
clearInterval(timerId);
}
});
}
function updateTimerView(){
//UI related code goes here
}
我假设change:context
仅在上下文(在我的例子中是templaylist
)更改时才会触发,但事实证明,当曲目更改、播放或暂停时也会触发。这不是所需的功能。。。否则,它将无法实现让change:track
和change:playing
事件播放的目的
这给我带来了很多麻烦,主要是因为当曲目被更改、播放或暂停时,会调用
contextChanged
,但是player.context.uri
没有更改,所以越来越多的计时器不断被添加。我在这里遗漏了什么?我同意,看起来像个虫子。我可能会把它改成这样
require(['$api/models'], function(models) {
models.player.addEventListener('change:context', contextChanged);
var last_context=null;
function contextChanged(e) {
if(last_context != e.oldValue.uri) {
last_context = e.oldValue.uri;
console.log('hola, new context uri - ' + last_context);
}
else {
console.log('faux context change');
}
}
});
谢谢你的帮助,结果很好。需要注意的是,
e.oldValue
每隔一段时间就会返回null。在添加了一个检查之后,一切似乎都很正常。当然,您可能希望使用e.target.context.uri而不是oldValue.uri(因为它是旧值)。