1

我试图通过点击 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/

4

3 回答 3

10

您必须将函数引用传递给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);

注意:通常的做法是仅使用大写首字母作为构造函数名称,因此您可以快速区分它们。这就是我将 and 重命名为and的Drink原因。Handledrinkhandle

于 2013-01-11T20:01:45.867 回答
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);
于 2013-01-11T20:03:18.123 回答
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);
        }

    }
}
于 2014-04-07T14:47:36.997 回答