3

I'm playing with Riot.js and everything is working great. But let's say I have a page where I mounted this single tag:

<so-example>

  <input type="text />

  <script>
    this.disabled = false
  </script>

</so-example>

Let's say I want to query this element for one of its properties (e.g. if it's disabled). Neither of these two approaches work:

  1. document.getElementsByTagName('so-example')[0].disabled
  2. document.querySelector('so-example').disabled

Both of these statements return undefined. I want my tag's DOM API to reflect its state, but can't figure out what I'm missing here.

bjork24
  • 3,153
  • 7
  • 35
  • 46

3 Answers3

3

For anyone who finds themselves in the same situation, the answer is to query the _tag property on the element. To access the disabled property of the element I used in my original question, you could do this:

document.querySelector('so-example')._tag.disabled

And that should return the expected false. Anything that's defined on this within the component can be accessed this way.

bjork24
  • 3,153
  • 7
  • 35
  • 46
  • This solution is not using the standard riot.js API and hence may not be future proof. In a future implementation of riot, `_tag` may not stand for what it is now. I would second the solution given by @vitomd: `var s; riot.compile(function() { s = riot.mount('so-example')[0]; }); console.log(s.disabled);` – ghd Nov 08 '16 at 09:16
  • @ghd Sadly, `.mount()` doesn't return anything anymore so we're forced to use non-standard API to do useful things. – Brad Feb 09 '19 at 05:05
0

I may be wrong for I have never used riot.js and it could do some kind of magic compilation that does that for you, but I doubt it, that sounds like overkill...

Attributes on custom elements don't get bound to their JS representation. You can't use .disable as a shortcut because the querySelector or getElementByWhatever function returns a HTMLUnknownElement which doesn't have any bound attributes. So you have to use getAttribute('disabled'); or hasAttribute('disabled'); instead.

Domino
  • 6,314
  • 1
  • 32
  • 58
0

It´s depends from where you want to access the property. For instance if it´s from a parent tag, then you can go with. this.tags.child.message (to access the message property from the child)

<example>
  <child></child>
  <button onclick={access_child}>access child</button>
  <script>
      access_child() {
        console.log(this.tags.child.message) 
      }
  </script>
</example>

<child>
  <script>
      this.message = 'Hello Riot'
  </script>
</child>

If you want to access from index.html, you should wrap the mount with riot.compile like this

<script type="text/javascript">
    riot.compile(function() {
      var example_tag = riot.mount('example')[0]
      var child_tag = example_tag.tags.child
      console.log('from index: '+child_tag.message)
    })
</script>

Here is a working example http://plnkr.co/edit/mjLlDozVzzfcv3Nwl63Y?p=preview

vitomd
  • 806
  • 7
  • 14