在Prototype上使用addEventListener

时间:2013-01-11 19:59:05

标签: javascript javascript-events

我试图通过点击addEventListener来破坏Prototype的结果,但结果显示甚至没有点击。

<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/

3 个答案:

答案 0 :(得分:9)

您必须将函数引用传递给addEventListener,而不是像您一样调用函数(并传递其返回值):

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

当你这样做时,你的处理程序只会在点击时触发。但是您将遇到一个不同的问题:处理程序中的this将是单击的元素,而不是您的Machine实例。要解决此问题,您可以使用Function.bind(请参阅旧版浏览器的polyfill的链接文档):

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

注意:通常的做法是仅对构造函数名称使用大写首字母,因此您可以快速浏览它们。这就是我将DrinkHandle重命名为drinkhandle的原因。

答案 1 :(得分:2)

您需要在侦听器的function(){}闭包之间添加调用。或者在函数名后删除()。

这应该有效: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);

答案 2 :(得分: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);
        }

    }
}