2016-10-13 42 views
2

我在玩Riot.js,一切都很好。但是,假设我有一个页面,我登上这个单一标签:从DOM访问Riot.js标记的属性

<so-example> 

    <input type="text /> 

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

</so-example> 

比方说,我想查询该元素的属性之一(例如,如果它被禁用)。无论是这两种方法的工作:

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

这些语句都返回undefined。我希望我的标签的DOM API能够反映它的状态,但是不知道我在这里丢失了什么。

回答

2

对于任何发现自己处于相同情况的人,答案是查询元素上的_tag属性。要访问我在我原来的问题使用的元素的disabled属性,你可以这样做:

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

,并应返回预期false。可以通过这种方式访问​​组件中的this中定义的任何内容。

+0

该解决方案不使用标准的riot.js API,因此可能不会成为未来的证明。在未来的暴乱实施中,'_tag'可能并不代表现在的情况。我会第二个由@vitomd给出的解决方案:var s; riot.compile(function(){s = riot.mount('so-example')[0];});的console.log(s.disabled);' – ghd

0

我可能是错的,因为我从来没有使用过riot.js,它可以做某种神奇的汇编,做,对你,但我对此表示怀疑,这听起来有点小题大做......定制

属性元素不会被绑定到他们的JS表示。您不能使用.disable作为快捷方式,因为querySelector或getElementByWhatever函数返回没有任何绑定属性的HTMLUnknownElement。因此,您必须改用getAttribute('disabled');hasAttribute('disabled');

0

这取决于你想要访问的属性。例如,如果它来自父标签,那么您可以随身携带。 this.tags.child.message(访问来自孩子的信息属性)

<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> 

如果你想从index.html的访问,你应该换安装与riot.compile这样

<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> 

这里是一个工作示例http://plnkr.co/edit/mjLlDozVzzfcv3Nwl63Y?p=preview