javascript 在Prototype上使用addEventListener

2admgd59  于 2023-04-10  发布在  Java
关注(0)|答案(3)|浏览(145)

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

wn9m85ua

wn9m85ua1#

你必须向addEventListener传递一个函数 reference,而不是像你这样调用函数(并传递其返回值):

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

bybem2ql

bybem2ql2#

你需要为你的监听器添加一个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);
of1yzvn4

of1yzvn43#

为了在对象上执行自定义事件,我使用这个简单的脚本来扩展我的对象:

/* 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);
        }

    }
}

相关问题