Matt-Esch / virtual-dom

A Virtual DOM and diffing algorithm
MIT License
11.66k stars 779 forks source link

Setting js-only properties on an Element #334

Closed viveleroi closed 8 years ago

viveleroi commented 8 years ago

I'm trying to determine the best way to set an indeterminate state for a checkbox input element. Because this is a property accessible only via javascript, I don't believe vdom has any options I can pass to h() to set this value.

jgaskins commented 8 years ago

Is there a purely vdom-way I can set this value?

Same as any other DOM-node property. :-)

h('input', {
  type: 'checkbox',
  indeterminate: true,
})

Every property you set with virtual-hyperscript gets set on the resulting DOM node, even if it's not part of the JS DOM API. I found this out by accident; I misspelled a property name.

If not, what's the recommended way for obtaining the resulting html element after rendering?

Most of the time when you need the resulting DOM element, you would use a hook. It's unnecessary here (which is great because this 2x as much code), but it could be done:

var IndeterminateSettingHook = function() {}

// The node arg is the actual DOM node that gets rendered, not a vdom node.
IndeterminateSettingHook.prototype.hook = function(node) {
  node.indeterminate = true;
}

h('input', {
  // It doesn't matter what you call the property you assign it to, but "hook" isn't a bad one.
  hook: new IndeterminateSettingHook(),
  type: 'checkbox',
};
viveleroi commented 8 years ago

That's immensely helpful, thanks. Unfortunately I'm blocked on using checkboxes entirely until I have a fix for #335