Search code examples
javascriptdom-events

Using addEventListener on Prototype


I am trying to run the results of Prototype via a click through addEventListener but the results are showing even without clicking.

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


Solution

  • You need to add your call between a function() {} closure for your listener. Or remove the () after your function name.

    This should work: 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);