动态自动链接实例变量到javascript / jquery中的对象函数?

时间:2009-12-05 06:02:44

标签: javascript jquery function oop

我正在尝试用javascript(& jQuery)创建一个强大的音频播放器。我知道还有其他玩家,但我想尝试自己创建(所以请不要将我引用到jquery插件)。这基本上就是我想做的事情:

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:

Player = 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
   }
}

基本上,我希望在初始化播放器时将属性预先链接到对象函数,并在将它链接到HTML元素时让它工作。

谢谢! 马特穆勒

2 个答案:

答案 0 :(得分:0)

我认为这将是一个更有用的方式。在Player中设置两个以上的功能。一个函数将UI元素注册到Player操作,另一个函数注销该操作。因此,您可以依靠jQuery.live和jQuery.die而不是保持明确的按钮集合。例如:

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]);
}

然后,上面的main.js示例将成为:

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

你的玩家构造函数将成为:

Player = function(Audio) {
    this.Audio = Audio;        
}

或类似的东西。

答案 1 :(得分:0)

这不是完美的解决方案,但我发现它非常优雅:

<强> 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();

这提供了一种将按钮链接到函数的好方法,而无需传入大量数组或提供大量选项。我非常乐意有一个不需要你调用init()的解决方案。