2013-01-11 56 views
1

我想通過點擊addEventListener來顯示Prototype的結果,但即使沒有點擊也會顯示結果。在原型上使用addEventListener

<div id="box">Your Item:</div> 

<button id="myBtn">Buy</button> 

<script type="text/javascript"> 
function Machine(n,p){ 
this.name = n; 
this.price = p; 
} 


Machine.prototype.Dispatch = function(){ 
var container = document.getElementById('box'); 
container.innerHTML = this.name + " " + this.price; 
} 
var Drink = new Machine("coke",80); 
var Handle = document.getElementById('myBtn'); 
Handle.addEventListener("click",Drink.Dispatch(),false); 
</script> 

http://jsfiddle.net/9trqK/

回答

2

您需要在您的偵聽器的函數(){}閉包之間添加您的調用。或者在您的函數名稱後面刪除()。

這應該工作:http://jsfiddle.net/9trqK/1/

function Machine(n, p) { 
    this.name = n; 
    this.price = p; 
} 
var handle = document.getElementById('myBtn'); 
Machine.prototype.Dispatch = function() { 
    var container = document.getElementById('box'); 
    container.innerHTML = this.name + " " + this.price; 
} 
var Drink = new Machine("coke", 80); 
handle.addEventListener("click", function() { Drink.Dispatch() }, false); 
9

你要通過一個函數參考addEventListener,而不是調用函數(並通過其返回值)爲你做的:

Handle.addEventListener("click", Drink.Dispatch, false); 

當你這樣做,你的處理程序只會在點擊時被解僱。但是你將面臨一個不同的問題:處理器內部的this將被點擊元素,而不是你的Machine實例。爲了解決這個問題,你可以使用Function.bind(見鏈接的文檔的填充工具舊版本瀏覽器):

var drink = new Machine("coke",80); 
var handle = document.getElementById('myBtn'); 
handle.addEventListener("click", drink.Dispatch.bind(drink), false); 

注:這是常見的做法是隻使用構造函數名大寫首字母,這樣你就可以告訴他們快速瀏覽一下。這就是爲什麼我重命名爲DrinkHandledrinkhandle

0

要做到自定義事件的對象我用這個簡單的腳本來延長我的對象:

/* Simple Custom event prototype for objects 

Extend your object like this: 

<OBJECT>.prototype = new EventEmitter; 

Then you can use : 

<OBJECT>.on("test",function() { alert("Test event triggered"); }) 
<OBJECT>.on("test",function() { alert("Test event 2 triggered"); }) 
<OBJECT>.trigger("test"); 

*/ 
function EventEmitter() { 

    var listeners = Object(); //Matrix of event/callbacks 

    //Add listener 
    this.on = function(evt, callback) { 
     //console.log("Listener added: " + evt); 

     if (!listeners.hasOwnProperty(evt)) 
      listeners[evt] = Array(); 

     listeners[evt].push(callback);  
    } 

    //Call listeners 
    this.trigger = function(evt, params) { 
     //console.log("trigger called " + evt); 
     //console.dir(listeners); 

     if (evt in listeners) { 
      callbacks = listeners[evt]; 
      //Call all callbacks with the params 
      for (var x in callbacks){ 
       callbacks[x](params); 
      } 
     } else { 
      console.log("No listeners found for " + evt); 
     } 

    } 
}