2016-05-17 75 views
0

我想使用元素中定义的函数。像这样:如何在模板聚合物中使用元素函数?

<template> 
<span onclick="this.parentElement.test();"></span> 
</template> 

<script> 
Polymer({ 
    is: 'test-ele', 
    test: function() { 
    console.log('This is a test message.') 
    } 
}) 
</script> 

有没有类似的方法?

<template> 
<span onclick="{{{test}}}"></span> 
</template> 

回答

0

给事件侦听器添加到本地DOM的孩子,在你的模板中使用导通事件注解。这通常不需要仅为了绑定事件监听器而给元素一个id。

来源:https://www.polymer-project.org/1.0/docs/devguide/events.html#annotated-listeners

<dom-module id="test-ele"> 
    <template> 
    <span on-click="test">Click Here</span> 
    </template> 

    <script> 
    Polymer({ 
     is: 'test-ele', 
     test: function() { 
     console.log('This is a test message.'); 
     } 
    }); 
    </script> 
</dom-module> 
0

简单的答案是no, you can't<span onclick="{{{test}}}"></span>将尝试启动功能{{{test}}},而不是将其作为模板变量读取。

此外,你的第一个例子是错误的。

<template> 
<span onclick="this.parentElement.test();"></span> 
</template> 

将尝试加载this.parentElement.test();作为函数。只需使用

<template> 
<span onclick="test"></span> 
</template> 

聚合物知道它应该在父元素中调用一个函数。