2016-05-17 76 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> 

聚合物知道它應該在父元素中調用一個函數。