0

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;"

6
  • Why not do this with CSS? Commented Oct 29, 2018 at 22:03
  • 1
    Those aren't really classes - they're object constructor functions Commented Oct 29, 2018 at 22:04
  • 2
    you need to return 'this' for chaining to happen Commented Oct 29, 2018 at 22:05
  • @tadman the background color changes are just for this example. I plan to put ajax calls etc within these events. Commented Oct 29, 2018 at 22:27
  • It's best to put in dummy code then instead of making it seem like all you're trying to do is change the background. Minimal code tries to focus on the problem without getting caught up in details. Commented Oct 29, 2018 at 22:30

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

thank you, this explains the chaining. But how would I be able to pass in code to/run as in my example, instead of the integers shown here? As im trying to set up events to run code.
@Jason do you want to send an anonymous method as an argument? I have added the stackblitz sample , I hope that you are expecting that. caller can decide what code need to be execute
I got it to work as i wanted, thanks for your help! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.