如何识别启动 core-ajax 调用的自定义元素(来自 core-ajax 响应)

How to identify the custom-element that started a core-ajax call (from the core-ajax response)

我正在使用 Polymer 生成自定义元素列表 (post-card)。 在每个自定义元素内都有一个图像的缩略图,单击时将展开并显示 "original image"。 "original image" link 是从对 imgur API 的 ajax 调用的响应中获得的(具有核心-ajax 组件)。

我尝试了这两条路线...但我仍然不确定最佳解决方案:

1.在每个 post-card 元素中使用核心-ajax 组件。

这个解决方案似乎可行,但在我看来它远非优雅。

2。使用单个核心-ajax 组件来管理每个 API 请求。

Post-list.html

<core-ajax 
  url="{{imgur_url}}"
  handleAs="json"
  on-core-response="{{handleResponse}}">
</core-ajax>

<template repeat="{{post, postIndex in posts}}">
    <post-card post={{post}} id={{postIndex}} on-img-tap={{imgurRequest}}>
</template>

这个解决方案我面临的主要问题是,当我从 core-ajax 得到响应时,我无法识别自定义元素 (post-card)哪个发送了请求。

我想过创建一个新的自定义元素扩展 core-ajax,允许我将 post-card 的 ID 作为参数传递(并在响应中取回)发送了请求...但我认为必须有更简单的解决方案,对吗?

提前致谢。

我假设您的 imgurRequest 函数中有类似 this.$.ajaxId.go(); 的内容(关于您的第二个解决方案)。您可以做的是通过 ajax 参数发送 postIndex。您的 imgurRequest 看起来有点像这样:

imgurRequest: function(e, detail, sender) {
  var postIndex = e.target.templateInstance.model.postIndex;
  // Set a property (to postIndex) which is bound to ajax parameter list here ...
  this.$.ajaxId.go();
}

这样您就可以在使用相同功能和相同核心-ajax 元素的同时区分您的 post 卡片。服务器当然应该将收到的 id 发送回客户端。