Let Me Tink About It
Let Me Tink About It

Reputation: 16122

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

Upvotes: 1

Views: 351

Answers (2)

Let Me Tink About It
Let Me Tink About It

Reputation: 16122

You can access the json data with ajax.lastResponse inside the added event listener.

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
    console.log('ajax', ajax.lastResponse);            
});
ajax.generateRequest();

Upvotes: 1

elvomka
elvomka

Reputation: 46

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();

Upvotes: 3

Related Questions