Thursday, February 16, 2012

How to pass data from markup to JS

Imagine we have some component system, similar to Dojo. Kernel find nodes, detects which components (let's call them widgets) they going to be coming from className or anything else. After that kernel must instantiate widgets and pass respective nodes and parameters.

So, we became all declarative and such, and it's just reasonable to store parameters near our node.

In my practice I saw three ways of doing that.

Usage of expando attributes (like Dojo does) or data- attributes (Bootstrap components).
May stretch yor node to several LOC. You can make it shorter using JSON instead of several attributes, to make it faster and less verbose, but JSON requires keys in double quotes, and it conflicts with markup if you used to double quotes around attributes values
Putting data in input[type=hidden] that resides inside your widget.
Name attribute became key and value of input became, er, value. Seems reasonable and may be useful, if your server-side puts extra data for itself in hidden inputs when rendering forms. But you should specify names inside your widget's code. Performance also suffer due to numerous DOM queries.
Just write your params in like Javascript's hash, prepend it with return keyword, and put it into onclick attribute.
Not very semantic and all, but this way has several advantages, which I describe next.

Pros of putting params through onclick:

  1. It's not JSON, so it wont conflict with markup.
  2. You don't need neither JSON.parse nor eval (which is evil). You just call it as function — as easy as var params = node.onclick().
  3. Some code editors can highlight JavaScript code inside onclick. So less typos, no missed parens and quotes, less bugs.
  4. Though it is not semantic usage of attributes, it can't break anything. Validator wont complain either.


  1. Not semantic. Purists gonna pure.
  2. It fires every time you click widget. Though it doesn't do much of job, performance can suffer slightly, I suppose. But you can use some other attribute — e.g. ondblclick. Double clicks rarely appears and rarely occurs in modern interfaces. Anyway, it's minor impact and minor flaw of method.
  3. It can be hard to exlain this to people. Use this article as reference:)

Pros wins!

I'm not inventor of this method parameters passing. I first met this approach while working at Yandex. JS in most their services use it; developer and browsers both seems happy with it.

No comments: