简体   繁体   English

如何在聚合物元素中调用函数

[英]how to call function within a polymer element

While reading the implementation of the core-xhr element by the Polymer team, the comments indicated that we could use the following method to use the element to perform XMLHttpRequests 在阅读Polymer团队阅读core-xhr元素的实现时,注释表明我们可以使用以下方法来使用该元素来执行XMLHttpRequests

* core-xhr can be used to perform XMLHttpRequests.
*
*     <core-xhr id="xhr"></core-xhr>
*     ...
*     this.$.xhr.request({url: url, params: params, callback: callback});

the request() method is declared within the polymer declaration as follow request()方法在聚合物声明中声明如下

Polymer('core-xhr', {
     request: function(options) {...},
     toQueryString: function(params) {....},
                ....
});

I will like to create a non-ui element where I could, using JavaScript, call on the methods declared within the non-ui element as demonstrated. 我想创建一个非ui元素,我可以使用JavaScript调用非ui元素中声明的方法。 It will seem that the method above was declared normally but I was unable to access my method. 似乎上面的方法被正常声明,但我无法访问我的方法。

My test element 我的测试元素

<polymer-element name="test-element" attributes="url">
<template>

</template>
<script>
    Polymer({
        url:"",
        alert: function()
        {
            alert("alert!");
        }           
    });
</script>
</polymer-element> 

My test page 我的测试页面

<body>
    <test-element id = "test"></test-element> 
    <script>
       $('#test').alert();
    </script
</body>

I was given a Uncaught TypeError: undefined is not a function . 我得到了一个Uncaught TypeError: undefined is not a function Does anyone know if I missed anything out or there was issue with how i called my alert method? 有没有人知道我是否错过了什么或者我是如何调用我的警报方法的?

Thanks 谢谢

It's because your trying to call the api on the jquery wrapper. 这是因为你试图在jquery包装器上调用api。 Instead either use $('#test').get(0).alert() to get the element interface or even better make a direct call using document.querySelector("#test").alert() 相反,要么使用$('#test')。get(0).alert()来获取元素接口,要么更好地使用document.querySelector(“#test”)进行直接调用.warning()

  $(document).ready(function() { $('#test').get(0).alert(); }); // without jquery // document.querySelector("#test").alert() 
 <script src="https://www.polymer-project.org/components/webcomponentsjs/webcomponents.js"></script> <link rel="import" href="https://www.polymer-project.org/components/polymer/polymer.html"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <polymer-element name="test-element" attributes="url"> <template> </template> <script> Polymer({ url: "", alert: function() { alert("alert!"); } }); </script> </polymer-element> <test-element id="test"></test-element> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM