Проверка полимера на наличие точек вставки

Я начинаю изучать Polymer 1.0, и я не мог понять, как программно искать точки вставки. Я понимаю, что мог бы обернуть <div> вокруг тега <content> и проверить, есть ли у этого <div> дочерние элементы или нет, но это требует рендеринга <div> для каждого элемента, что кажется расточительным. Есть ли способ с помощью JavaScript проверить, были ли загружены какие-либо точки вставки? В идеале у меня была бы функция thereAreInsertionPoints, которая определяла бы, будет ли отображаться тег <p>. Мой код полимера выглядит так:

  <template>
      <h1>{{title}}</h1>
      <p>{{body}}</p>
      <content id="content"></content>
      <p if="{{thereAreInsertionPoints()}}">There are insertion points!</p>

  </template>

  <script>
    Polymer({
      is: "post-content",
      properties: {
        title: String,
        body: String
      },
      thereAreInsertionPoints: function(){
        //determine whether or not we have insertion points
      }
    });

  </script>

person mjkaufer    schedule 15.07.2015    source источник


Ответы (1)


Существуют различные Polymer API для работы с DOM включая Content API.

API контента:

  • Polymer.dom(contentElement).getDistributedNodes()

  • Polymer.dom(узел).getDestinationInsertionPoints()

Эти API можно использовать различными способами для проверки распределенных узлов и точек вставки. Я создал рабочую реализацию, которая показывает элемент post-content с дополнительными методами для проверки распределенных узлов и точек вставки назначения.

<script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import"
      href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">
<dom-module id="post-content">
	<template>
		<h1>{{title}}</h1>
		<p>{{body}}</p>
		<content></content>
		<template is="dom-if" if="{{destinationInsertionPointsExist()}}">
			<p>Destination insertion point(s) exist.</p>
		</template>
		<template is="dom-if" if="{{distributedNodesExist()}}">
			<p>Distributed node(s) exist.</p>
		</template>
	</template>
	<script>
		Polymer({
			is: "post-content",
			properties: {
				title: String,
				body: String
			},
			destinationInsertionPointsExist: function () {
				var distributedNodes = Polymer.dom(this).childNodes;

				var countDestinationInsertionPoints = 0;
				distributedNodes.forEach(function (distributedNode) {
					var distributedNodeHasDestinationInsertionPoints = Polymer.dom(distributedNode).getDestinationInsertionPoints().length > 0 ? true : false;

					if (distributedNodeHasDestinationInsertionPoints) {
						countDestinationInsertionPoints++;
					}
				});

				return countDestinationInsertionPoints > 0 ? true : false;
			},
			distributedNodesExist: function () {
				var contentNodes = Polymer.dom(this.root).querySelectorAll("content");

				var countDistributedNodes = 0;
				contentNodes.forEach(function(contentNode) {
					var contentNodehasDistributedNodes = Polymer.dom(contentNode).getDistributedNodes().length > 0 ? true : false;

					if (contentNodehasDistributedNodes) {
						countDistributedNodes++;
					}
				});

				return countDistributedNodes > 0 ? true : false;
			}
		});
	</script>
</dom-module>

<post-content title="This is the title" body="This is the body">
	<p>This is distributed content</p>
</post-content>

Несколько замечаний по коду:

  • Я сделал много имен переменных и тройных проверок очень подробными для ясности в этом ответе. Изменения могут быть внесены для упрощения кода.

    Например:

    var distributedNodeHasDestinationInsertionPoints = Polymer.dom(distributedNode).getDestinationInsertionPoints().length > 0 ? true : false;

    может стать чем-то вроде

    var hasInsertionPoints = Polymer.dom(distributedNode).getDestinationInsertionPoints().length

  • Используйте новый условный шаблон (Polymer 1.0) dom-if.

    <p if="{{thereAreInsertionPoints()}}">There are insertion points!</p>

    становится

<template is="dom-if" if="{{destinationInsertionPointsExist()}}">
    <p>Destination insertion point(s) exist.</p>
</template>
  • Я бы рекомендовал пройтись по методам destinationInsertionPointsExist и distributedNodesExist, чтобы убедиться, что вы полностью понимаете, что на самом деле проверяется. Возможно, вам придется изменить эти методы в соответствии с вашими конкретными потребностями и требованиями.

    • Например, даже если у вас есть один пробел между начальным и конечным тегами элемента post-content, оба этих метода вернут true.

      <post-content title="This is the title" body="This is the body"> </post-content>

person coderfin    schedule 15.07.2015
comment
Спасибо за ясность. Я пытался сделать то, о чем вы говорили, но безрезультатно, но я думаю, что проблема, как вы упомянули, заключалась в том, что между тегами <post-content> был пробел. Спасибо еще раз! - person mjkaufer; 16.07.2015