5

I currently have an object which I want to pass as a parameter to another function inside a template literal:

    var template = `<button onclick="onclick(${object})"></button>`;

However, this makes the parameter become a string value: [object Object] and doesn't pass the parameter. Is there any way to pass this parameter into the function?

Thank you very much in advance.

danwillm
  • 469
  • 3
  • 17
  • 1
    There is no function inside that template literal, it's just a string, and your object is string-interpolated as well. Don't use `onclick` event handler attributes, install the event listener function properly! – Bergi Sep 05 '19 at 19:12
  • That you don't need to deal with object serialisation and deserialisation, not with js escaping, not with html escaping, not with the weird scopes of attribute event handlers, that you actually get to use the real object (same identity), and that it is more efficient. See https://stackoverflow.com/q/6941483/1048572 – Bergi Sep 05 '19 at 20:23

1 Answers1

4

You are going to need to represent your object as a string. You can do this using JSON.stringify:

var template = `<button onclick="handleClick(${JSON.stringify(obj).split('"').join("&quot;")})"></button>`;

You will need to escape double quotes (which this code does), and single quotes if used for your onclick event (this code doesn't).

onclick="onclick" actually calls window.onclick - meaning that it picks up clicks anywhere. You should use a different name (such as handleClick).

I would suggest refraining from using inline event listeners for reasons like this, and because they can cause issues if you ever need to adopt a content-security-policy.

ecc521
  • 576
  • 6
  • 14
  • 1
    and how would I be able to turn it back into an object? – danwillm Sep 05 '19 at 19:03
  • Javascript should evaluate the stringified code as an object. JSON is a stricter form of Javascript object literals. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Syntax – ecc521 Sep 05 '19 at 19:05
  • However if you need to convert a JSON string to an object, you can run ```JSON.parse(string)``` – ecc521 Sep 05 '19 at 19:06
  • Your warning misses the point. It still fails for `{example: "apostrophe: ' "}`. What you actually need to do is html-entity-escape the string after serialising the object. – Bergi Sep 05 '19 at 19:14