【问题标题】:How to identify the custom-element that started a core-ajax call (from the core-ajax response)如何识别启动 core-ajax 调用的自定义元素(来自 core-ajax 响应)
【发布时间】:2015-04-27 10:17:40
【问题描述】:

我正在使用 Polymer 生成自定义元素列表(明信片)。 在每个自定义元素内都有一个图像缩略图,单击该缩略图会展开并显示“原始图像”。 “原始图像”链接是从对 imgur API 的 ajax 调用的响应中获得的(带有 core-ajax 组件)。

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

1.在每个明信片元素中使用 core-ajax 组件。

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

2。使用单个 core-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 获得响应时,我无法识别发送请求的自定义元素(明信片)。

我考虑过创建一个扩展 core-ajax 的新自定义元素,允许我将发送请求的明信片的 ID 作为参数(并在响应中取回)传递...但我认为应该是更简单的解决方案吧?

提前谢谢你。

【问题讨论】:

    标签: javascript ajax polymer


    【解决方案1】:

    我假设您的 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();
    }
    

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

    【讨论】:

    • 这正是我想做的,但我不知道可以为代码ajax分配一个参数并在响应中取回它......我以为是只是服务器使用的参数。但我错了,如果我在 core-ajax 中这样做,我可以在响应中得到它:params='{"postId": "{{postId}}"}' 谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多