希望我能很好地表达这个问题。我正在使用Titanium Desktop中的简单音频播放器。我现在关注的主要代码如下:
function pickMusicFolder (){
var win = Titanium.UI.getCurrentWindow();
win.openFolderChooserDialog(function(folderResponse) {
var file = Titanium.Filesystem.getFile(folderResponse[0]);
var listing = file.getDirectoryListing();
for (var i = 0; i < listing.length; i++) {
if (listing[i].isDirectory()) {
// if the listing is a directory, skip over it
$('#main').append('DIRECTORY: ' + listing[i].nativePath() +
'<br />');
// continue;
}
else {
// otherwise, print the filename of the file to the #main content window
var songOnList = listing[i].nativePath();
var songURL = songOnList.replace(/\\/g,"/");
$('#main ul').append('<li><a href="javascript:playSong(\'' + songURL + '\')">' + songURL + '</a></li>');
}
}
});
};
function playSong(songURL){
var currentSong = Titanium.Media.createSound(songURL);
currentSong.play();
this.stopPlayback = stopPlayback;
function stopPlayback(currentSong){
currentSong.stop();
}
}
然后是相关的HTML:
<input type="image" src="img/player_stop.png" name="stopPlayback" onClick="playSong.stopPlayback(songURL)" />
<input type="image" src="img/folder_add.png" name="pickMusicFolder" onClick="pickMusicFolder()" />
现在,pickMusicFolder和playSong本身都能正常工作。但是,stopPlayback无法正常工作,我很难掌握如何处理播放和停止音频的不同功能,因为生成可点击链接的代码在pickMusicFolder函数中完全划分,而停止代码播放仅附加到一个单独的界面按钮。
我只需要在多个函数之间访问songURL变量,以便能够在播放(或不播放)时对一首单独的歌曲执行操作。我正在避免使用全局变量,因为我发现它是一种警察。
有人有什么想法吗?任何提示都非常感谢! (哦,请忽略我丑陋的代码;在发布之前尝试了一堆hack-y解决方案。)
答案 0 :(得分:3)
非常快速的解决方案是将currentSong
存储为函数playSong
的属性:
function playSong(songURL){
var currentSong = Titanium.Media.createSound(songURL);
playSong.currentSong = currentSong; // store curernt playing song as property of function
currentSong.play();
}
playSong.stopPlayback = function() {
if (playSong.currentSong) {
playSong.currentSong.stop();
delete playSong.currentSong;
}
};
当歌曲停止时,只需删除此属性,这意味着现在没有播放歌曲
答案 1 :(得分:1)
你应该使用一个闭包。见下文
var stopPlayback = function() { /* Placeholder, defined later */ };
var playSong = function(songURL){
var currentSong = Titanium.Media.createSound(songURL);
currentSong.play();
// Redefine stopSong in the parent scope
stopPlayback = function(){
// currentSong is available to this function via closure
currentSong.stop();
}
}
HTML编辑
<input type="image" src="img/player_stop.png" name="stopPlayback" onClick="stopPlayback()" />
作为旁注,您不应该使用HTML属性来附加JavaScript事件。 This is a great series on event attachment,但您真正应该阅读的是this part。此外,每个JS库都提供了附加事件的方法,使您的生活更轻松。