I'm trying to create a robust audio player in javascript (& jQuery). I know that there are other players out there, but I'd like to try creating my own (so please don't refer me to jquery plugins). This is essentially what I would like to do:
Main.js:
var player = new Player(AudioObj); // Audio object links to Audio class (not shown)
player.buttons.play = $('play');
player.buttons.pause = $('pause'); // Play and pause ID's link to HTML Document Element
Player.js:
Playe开发者_如何学Gor = function(Audio) {
this.Audio = Audio;
this.buttons = {};
for(var button in this.buttons) {
button.live('click', this.button); // This is the line I Have NO idea about..
}
}
Player.prototype = {
play : function() {
// Do Something
},
pause : function() {
// Do something
}
}
So essentially, I would like the properties to be pre-linked to object functions when you initialize the Player, and to just have it work when I link it to an HTML element.
Thanks! Matt Mueller
I think this would be a more OO way to go. Setup two more functions inside Player. One function would register a UI element to a Player action and another to unregister the action. So rather than keeping an explicit button collection you can just lean on jQuery.live and jQuery.die. For example:
function registerAction(selector, action) {
// you could have some logic to map the passed in action
// to the actual function name
$(selector).live('click', action/functionName);
}
function unRegisterAction(selector, [action]) {
// you could have some logic to map the passed in action
// to the actual function name
$(selector).die('click', [action/functionName]);
}
Then, your main.js example from above would become:
var player = new Player(AudioObj); // Audio object links to Audio class (not shown)
player.registerAction('#play', play);
player.registerAction('#pause', pause); // Play and pause ID's link to HTML Document Element
And your Player constructor would become:
Player = function(Audio) {
this.Audio = Audio;
}
Or something like that.
This is not the perfect solution but I find it to be pretty elegant:
Player.js
Player.prototype = {
init: function() {
var Player = this;
// Attach buttons to respected functions
for(var button in this.buttons) {
if(typeof Player[button] === "function")
$(this.buttons[button]).bind('click', {Player : this}, Player[button]);
}
},
play: function(e){
var Player = e.data.Player;
var Audio = Player.Audio;
Audio.play();
},
pause: function(e){
var Player = e.data.Player;
var Audio = Player.Audio;
Audio.pause();
}
}
Main.js
var audio = new AudioCore("UpToYou.mp3");
var player = new Player(audio);
player.buttons.play = $('#play');
player.buttons.pause = $('#pause');
player.init();
This provides a nice way to link buttons to the function without passing in a huge array or providing a bunch of options. I would be VERY happy to have a solution that would NOT require you to call init().
精彩评论