ajax - 使用 Polymer 实现声明式集合渲染的最佳方法是什么?

标签 ajax components polymer

我希望能够渲染使用 <core-ajax> 获取的远程集合像这样:

<rendered-collection url="/api/items">
  <custom-element value="{{ _it_ }}"></custom-element>
</rendered-collection>

哪里<rendered-collection>看起来像:

<link rel="import" href="/core-ajax/core-ajax.html">

<polymer-element name="rendered-collection" attributes="url" noscript>
  <template>
    <core-ajax url="{{ url }}" response="{{ collection }}" auto handleAs="json"></core-ajax>
    <template repeat="{{ _it_ in collection }}">
      <content><!-- cannot be used like that unfortunately --></content>
    </template>
  </template>
</polymer-element>

我意识到事情并非如此 <content>应该可以工作,但无论如何我仍然必须将模型注入(inject)其中。

我见过answers建议在 JS 中检索内容的节点:

<style>
  ::content > * {
    display: none;
  }
</style>
<content id="content"></content>
...
<script>
  Polymer('rendered-collection', {
    attached: function () {
      this.contentNodes = this.$.content.getDistributedNodes();
      // then...how do I inject models from the collection into the nodes?
    }
  });
</script>

最好的方法是什么?

最佳答案

如果我正确理解你的用例,你想要 <rendered-collection> 的 child 描述集合中每个项目的渲染。这正是<template>是为了.因此,如果我们建议使用 <rendered-collection>像这样:

<rendered-collection>
  <template>
    <h2>{{name}}</h2>
  </template>
</rendered-collection>

然后我们可以用一些 template-fu 来渲染它:

<polymer-element name="rendered-collection">
<template>
  <content></content>
</template>
<script>
  Polymer('rendered-collection', {
    collection: [
      {name: 'alpha'},
      {name: 'beta'},
      {name: 'gamma'}
    ],
    ready: function() {
      this.bindTemplate();
    },
    bindTemplate: function() {
      // user-supplied template
      var t = this.querySelector('template');
      // optional, but supplies fancy expression support
      t.bindingDelegate = new PolymerExpressions();
      // repeat over the entire model
      t.setAttribute('repeat', '{{}}');
      // set the model to our collection
      t.model = this.collection;
    }
  });
</script>
</polymer-element>

http://jsbin.com/kedig/1/edit

关于ajax - 使用 Polymer 实现声明式集合渲染的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24839612/

相关文章:

javascript - Polymer 1.X - 复杂的观察者不开火

javascript - 通过 .ajax() 发布 JSON 数组后无法读取 PHP 中的 NULL 变量

jquery - 如何将 jQuery 表单提交转换为 Ajax?

c++ - 如何改进 GetComponent<> 方法

java - JFrame 不呈现任何组件

Polymer,如何将值传递给需要字符串的 paper-date-picker 属性?

php - 使用 $.ajax 发布到 php

php - 仅接受来自经过身份验证的用户的某些 ajax 请求

c# - 可以从 WebClient 继承而我的代码不是 "design time component"吗?

Dart/polymer 加载屏幕?