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.
Nameattribute 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.
returnkeyword, and put it into
- Not very semantic and all, but this way has several advantages, which I describe next.
Pros of putting params through
- It's not JSON, so it wont conflict with markup.
- You don't need neither
eval(which is evil). You just call it as function — as easy as
var params = node.onclick().
onclick. So less typos, no missed parens and quotes, less bugs.
- Though it is not semantic usage of attributes, it can't break anything. Validator wont complain either.
- Not semantic. Purists gonna pure.
- 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.
- It can be hard to exlain this to people. Use this article as reference:)
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.
Post a Comment