1

here is my code, Now some people may say why not just include the one line code in that function block but i don't want to, how do i achieve that. How can i call this.click method on "click" event of the button

 var i = 0;
function el() {
    this.type = "button",
    this.el = false,
    this.click = function () {
        this.setHtml(i++);
    },
    this.setHtml = function (t) {
        this.el.innerHTML = t;
    }
    fragment = document.createDocumentFragment(),
        element = fragment.appendChild(document.createElement(this.type));
    element.setAttribute("data-el", this.type);
    element.innerHTML = "Default Button";
    this.el = element;
    attachEvent("click", this);
}
// this should be a seperate function ....
function attachEvent(ev, me){
//me doesn't work, but i want it to call the click method
    me.el.addEventListener("click", me.click, false);//....

}


div  = new el();
document.getElementById('areaA').appendChild(div.el);
Waqar Haider
  • 929
  • 10
  • 33

1 Answers1

1

Change this:

me.el.addEventListener("click", me.click, false);//....

to this:

me.el.addEventListener("click", me.click.bind(me), false);//....

When you pass only me.click, you are just passing a reference to the click function and the binding to me is lost. .bind() will create a self-binding stub function that will give you the right this value when the event handler is called.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 2
    +1 the problem is the context of the function, with bind you can select "this" context, here a link about what is bind: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Kalamarico Oct 07 '17 at 17:48
  • this is so cool, thanks man – Waqar Haider Oct 07 '17 at 17:48