我尝试将函数转换为字符串,并按如下方式传递:
var myfunc = function (name) {
alert('It works!' +name);
}
var as_string = myfunc.toString();
var contentHtml = "<my-element post='{"value":"" + target.value.toString() + "","update":"" + as_string + ""}'></my-element>"
但它没有正确地将其转换为字符串。当我签入开发工具时它显示如下:
<my-element style="z-index:2998; width:700px;" post="{"value":"USUNCLM","update":"function (name) {
alert("It works!' +name); }"}'></my-element>
转换为函数是在这里附加的JS Fiddle中工作的:https://jsfiddle.net/kavyapenujuru/L0m95396/
有没有其他方法可以将函数传递给聚合物元素?或者有其他方法可以改进我的解决方案吗?
这里是聚合物的工作示例:Plunk
在父元素中定义JavaScript对象:
domReady: function() {
// Animal properties and method encapsulation
this.animal = {
type: "Invertebrates", // Default value of properties
displayType : function(){ // Method which will display type of Animal
console.log(this.type);
alert(this.type);
}
}
},
将其传递给子元素:
<my-dynamic_element
animal='{{animal}}'>
</my-dynamic_element>
在子元素中使用:
domReady: function() {
console.log('in Dynamic:');
this.animal.displayType();
},
注意,当传递对象时,会扭曲单引号中的属性:
obj_attr='{{obj_attr}}'