Skip to content
This repository has been archived by the owner on Sep 23, 2022. It is now read-only.

Commit

Permalink
Add simple if-else switch support to the fill method, part of #28
Browse files Browse the repository at this point in the history
  • Loading branch information
kyoshino committed May 13, 2015
1 parent 2120c5f commit e81c9e2
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions scripts/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,36 @@ if (typeof String.prototype.includes !== 'function') {

FlareTail.util.content = {};

/*
* Fill DOM nodes with data using the Microdata API, and optionally set arbitrary attributes. This method also supports
* simple if-else switches in the markup; use the data-if and data-else attributes.
*
* Markup example:
* <span itemprop="creator" itemscope itemtype="http://schema.org/Person" data-attrs="title data-id">
* <meta itemprop="email">
* <span itemprop="name"></span>
* <span data-if="image">
* <img itemprop="image" alt="">
* </span>
* <span data-else>
* No image provided.
* </span>
* </span>
*
* JavaScript example:
* FlareTail.util.content.fill($bug.querySelector('[itemprop="creator"]'), {
* // Schema.org data
* 'name': 'Kohei Yoshino', 'email': 'kohei.yoshino@gmail.com', 'image': 'kohei.png'
* }, {
* // Attributes
* 'title': 'Kohei Yoshino\nkohei.yoshino@gmail.com', 'data-id': 232883
* });
*
* [argument] $scope (Element) an DOM element with the itemscope attribute
* [argument] data (Object) keys are the itemprop attribute
* [argument] attrs (Object) attributes to be set according to the data-attrs attribute
* [return] $scope (Element)
*/
FlareTail.util.content.fill = function ($scope, data, attrs = {}) {
let iterate = ($scope, data) => {
for (let [prop, value] of Iterator(data)) {
Expand Down Expand Up @@ -162,6 +192,18 @@ FlareTail.util.content.fill = function ($scope, data, attrs = {}) {
}
}

// Support simple if-else switches
for (let $if of $scope.querySelectorAll('[data-if]')) {
console.log($if, $if.getAttribute('data-if'), data[$if.getAttribute('data-if')], data);
// Hide the element if the data is undefined
let hidden = $if.hidden = !data[$if.getAttribute('data-if')],
$next = $if.nextElementSibling;

if ($next && $next.hasAttribute('data-else')) {
$next.hidden = !hidden;
}
}

$scope.removeAttribute('aria-busy');

return $scope;
Expand Down

0 comments on commit e81c9e2

Please sign in to comment.