Kavya Penujuru
Kavya Penujuru

Reputation: 37

How to pass a function object to a Polymer element from javascript

I tried converting function to a string and pass it as below:

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

But it is not converting it into string properly. When I checked in dev tools It appeared as below:

<my-element style="z-index:2998; width:700px;" post="{"value":"USUNCLM","update":"function (name) {
                    alert("It works!' +name); }"}'></my-element>

Converting to a function is working in JS Fiddle attached here: https://jsfiddle.net/kavyapenujuru/L0m95396/

Is there any other way to pass a function to Polymer element ? Or any other ways to improve my solution?

Upvotes: 2

Views: 2243

Answers (1)

Goce Ribeski
Goce Ribeski

Reputation: 1372

Here is Polymer working example: Plunk

Define the JavaScript object in the parent element:

 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);
          }
        }
  },

Pass it to the child element:

 <my-dynamic_element 
          animal='{{animal}}'>
  </my-dynamic_element>

Use it inside the child element:

 domReady: function() {
      console.log('in Dynamic:');
      this.animal.displayType();
  },

Note, when passing objects warp the attributes in single quotes:

 obj_attr='{{obj_attr}}'

Upvotes: 1

Related Questions