Search code examples
ajaxpolymerpolymer-1.0polymer-1.xiron-elements

Polymer 1.x: Using iron-ajax inside a custom behavior


I'm building a custom behavior. Call it MyBehaviors.MySpecialBehavior.

But I need to get data that's stored locally in a JSON file called my-data.json.

How can I do this inside my behavior? I'm trying to import iron-ajax but I can't think of how to access its methods or properties.

my-special-behavior.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">

<script>
  var MyBehaviors = MyBehaviors || {};
  MyBehaviors.MySpecialBehaviorImpl = {
    // Methods go here that rely on data at my-data.json
  };

  MyBehaviors.MySpecialBehavior = [
    MyBehaviors.MySpecialBehaviorImpl,
  ];
</script>
my-data.json
{
  "important": "data",
  "j": 5,
  "o": "N",
  "goes": "here"
}

Solution

  • You can create elements programatically. Have a look at how iron-ajax itself does that to use iron-request internally:

    https://github.com/PolymerElements/iron-ajax/blob/master/iron-ajax.html#L442

    Refering to your usecase, the user a1626 created this snippet:

    var ajax = document.createElement('iron-ajax');
    ajax.contentType = "application/json";
    ajax.handleAs = "json";
    ajax.url = <url goes here>
    ajax.method = 'get';
    ajax.addEventListener('response', function (event) {
        //response handler                  
    });
    ajax.generateRequest();