OLD | NEW |
(Empty) | |
| 1 <!-- |
| 2 Copyright 2013 The Polymer Authors. All rights reserved. |
| 3 Use of this source code is governed by a BSD-style |
| 4 license that can be found in the LICENSE file. |
| 5 --> |
| 6 <!-- |
| 7 /** |
| 8 * @module Polymer Elements |
| 9 */ |
| 10 /** |
| 11 * polymer-jsonp can be used to perform JSONP requests. |
| 12 |
| 13 * Example: |
| 14 * |
| 15 * <polymer-jsonp url="https://clients1.google.com/finance/info?q=GOOG&clien
t=ig&callback=" |
| 16 * response="{{data}}"></polymer-jsonp> |
| 17 * |
| 18 * @class polymer-jsonp |
| 19 */ |
| 20 /** |
| 21 * Fired when a response is received. |
| 22 * |
| 23 * @event polymer-response |
| 24 */ |
| 25 --> |
| 26 <link rel="import" href="../polymer/polymer.html"> |
| 27 |
| 28 <polymer-element name="polymer-jsonp" attributes="url response auto bustCache"> |
| 29 <script> |
| 30 (function() { |
| 31 Polymer('polymer-jsonp', { |
| 32 /** |
| 33 * The URL target of the request. |
| 34 * |
| 35 * @attribute url |
| 36 * @type string |
| 37 * @default '' |
| 38 */ |
| 39 url: '', |
| 40 /** |
| 41 * Returns the response object. |
| 42 * |
| 43 * @attribute response |
| 44 * @type Object |
| 45 * @default null |
| 46 */ |
| 47 response: null, |
| 48 bustCache: false, |
| 49 auto: false, |
| 50 urlChanged: function() { |
| 51 if (this.url && this.auto) { |
| 52 this.go(); |
| 53 } |
| 54 }, |
| 55 /** |
| 56 * Performs a JSONP request to the url specified. |
| 57 * |
| 58 * @method go |
| 59 */ |
| 60 go: function() { |
| 61 if (!this.isInFlight()) { |
| 62 this.callbackFunc = JSONP_CALLBACK_FUNC_NAME + callbackId++; |
| 63 window[this.callbackFunc] = this.respond.bind(this); |
| 64 var url = this.url + this.callbackFunc + (this.bustCache ? '&' + Mat
h.random() : ''); |
| 65 this.addScript(url); |
| 66 } |
| 67 }, |
| 68 isInFlight: function() { |
| 69 return !!this.script; |
| 70 }, |
| 71 addScript: function(inSrc) { |
| 72 this.script = document.createElement('script'); |
| 73 this.script.src = inSrc; |
| 74 this.script.onerror = this.respond.bind(this); |
| 75 var s = document.getElementsByTagName('script')[0]; |
| 76 s.parentNode.insertBefore(this.script, s); |
| 77 }, |
| 78 removeScript: function() { |
| 79 if (this.script.parentNode) { |
| 80 this.script.parentNode.removeChild(this.script); |
| 81 } |
| 82 this.script = null; |
| 83 }, |
| 84 respond: function(inResponse) { |
| 85 this.response = inResponse; |
| 86 this.removeScript(); |
| 87 delete window[this.callbackFunc]; |
| 88 this.fire('polymer-response', {response: inResponse}); |
| 89 } |
| 90 }); |
| 91 var JSONP_CALLBACK_FUNC_NAME = '_polymer_jsonp_callback_'; |
| 92 var callbackId = 0; |
| 93 })(); |
| 94 </script> |
| 95 </polymer-element> |
OLD | NEW |