Jason
Jason

Reputation: 403

javascript class with event methods

My goal is to make a class with some chained functions, but I'm stuck and hoping for some help. This is what I got:

robin = new batman("myiv");
var batman = (function() {
    var me = this;
    function batman(id){
        me._id=id;
        document.getElementById(id).addEventListener('mousemove', me.mouseMoving.bind(me),true);
    }
    this.mouseMoving = function(){
        document.getElementById(me._id).style.background="orange";
    }

    return batman;
}

And this pseudo code is what I am aiming to get. Basically, pass in the ID of an element in my HTML and chain functions to it such as onclick etc, and whatever code inside there, runs. as in example, changing background colors.

Is it possible?

superman("mydiv"){
    .onmouseover(){
        document.getElementById(the_id).style.background="#ffffff";
    },
    .onmouseout(){
        document.getElementById(the_id).style.background="#000000";
    },
    etc...
}

edit: updated with missing code: "return batman;"

Upvotes: 0

Views: 61

Answers (1)

Jameel Moideen
Jameel Moideen

Reputation: 7931

You can do method chaining by returning the current object using this keyword

var YourClass = function () {
  this.items = [];
  this.push = function (item) {
    if (arguments) {
      this.items.push(item);
    }
    return this;
  }
  this.count = function () {
    return this.items.length;
  }
}



var obj = new YourClass();
obj.push(1).push(1);
console.log(obj.count())

Working sample

https://stackblitz.com/edit/method-chaining-example?file=index.js

Upvotes: 3

Related Questions