0

Recently, I've asked a question about how to create a shortand for addEventListener, the result was:

var dom = {
  id: function(elementId) {
    var element = document.getElementById(elementId);
    return Object.create(element, {
      on: {
        value(event, fn, options) {
          element.addEventListener(event, fn, options);
        }
      }
    })
  }
};

what if I wanted to add two Object.create? How would I return it? Is it even possible?

8
  • If you want to add a second method, add it after on(). If you run Object.create again, you'll lose the on() method. Commented Feb 15, 2021 at 21:03
  • does it mean I have to do something like dom.id.funcName = function(param) {}? Commented Feb 15, 2021 at 21:06
  • @user14945188 I don't understand how this is supposed to work. When I create a div with id="el" and do dom.id("el").on("click", doThis());, it fires doThis() immediately and the click event isn't attached. Can you add the code showing its implementation? Commented Feb 15, 2021 at 21:43
  • 1
    Let's suppose you want to change the div's innerText, you have to do: dom.id('el').on('click', function() { this.innerText = 'text' }); Commented Feb 15, 2021 at 22:02
  • 1
    @symlink not doThis() it will fire function. Pass doThis without (). Commented Feb 15, 2021 at 22:15

1 Answer 1

1

If I understand your question correctly, you can add several functions to dom and chain them by returning this inside each function. Then call them like this:

dom.id("el").on("click",()=>console.log("clicked") ).changeText("replacement text");

var dom = {
  id: function(elementId) {
    var element = document.getElementById(elementId);
    return Object.create(element, {
      on: {
        value(event, fn, options) {
          element.addEventListener(event, fn, options);
          return this;
        }
      },
      changeText: {
        value(text) {
          element.innerText = text;
          return this;
        }
      }
    })
  }
};

dom.id("el").on("click", () => console.log("clicked") ).changeText("replacement text");
<div id="el">This text will be replaced</div>

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

Comments

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.