Tuesday, January 14, 2014

Day 996: Model Driven Views in Polymer (JS)


I adore switching back and forth between the JavaScript version of Polymer and Polymer.dart. It has been a fantastic feedback mechanism for validating or, more frequently, disproving my thinking about Polymer. Tonight, I switch back to the JavaScript in the hopes that I can solidify my thinking on model driven views in Polymer.

In my Dart version, I have a <x-pizza> Polymer that builds up a pizza for order. It looks something like:



And it works. More or less.

One thing that I was not quite able to figure out was why model attributes—specifically list model attributes—were not updating the values bound in templates. For instance, the model.firstHalfToppings and model.secondHalfToppings values are not being updated in the template when they change in the model:
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>
{{model.firstHalfToppings}}
{{model.secondHalfToppings}}</pre>
    <!-- ... -->
</template>
So let's see if I can make that work in a JavaScript version. Starting with the index.html page that contains my soon-to-exist-js-polymer:
<head>
  <!-- 1. Load Polymer before any code that touches the DOM. -->
  <script src="bower_components/platform/platform.js"></script>
  <!-- 2. Load component(s) -->
  <link rel="import" href="elements/x-pizza.html">
</head>
<body>
  <div class="container">
    <h1>JS Bros. Pizza Builder</h1>
    <x-pizza></x-pizza>
  </div>
</body>
The template that goes into the imported x-pizza-html is nearly identical to the Dart version. What changes is, obviously, the script tag—which now points to a JavaScript version of the Polymer class:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>
{{model.firstHalfToppings}}
{{model.secondHalfToppings}}</pre>
  <!-- ... -->
  </template>
  <script src="x_pizza.js"></script>
</polymer-element>
There is nothing too out of the ordinary in that backing Polymer class—just the model assignment in the ready() lifecycle method:
Polymer('x-pizza', {
  ready: function() {
    this.model = {
      firstHalfToppings: []
    };
  },
  addFirstHalf: function() {
    this.model.firstHalfToppings.push(this.currentFirstHalf);
  },
  // ...
});
The Polymer documentation recommends binding the model in ready() to avoid shared prototype state (ah, JavaScript).

In addition to assigning the model, I also define a bound method that adds records to the firstHalfToppings list property of the model. Whenever this function is called, the model's firstHalfToppings should change, which should update in the template. Only it did not in the Dart version of the Polymer.

And it does not in the JavaScript version either:



No matter how often I click that button, the variable bound in that template never updates.

Interestingly, if I create a string attribute directly on my Polymer and update it whenever the addFirstHalf() method is called:
Polymer('x-pizza', {
  ready: function() {
    this.model = {
      firstHalfToppings: [],
      secondHalfToppings: []
    };
  },
  pizzaState: '',
  addFirstHalf: function() {
    this.model.firstHalfToppings.push(this.currentFirstHalf);
    this.pizzaState = this.model.firstHalfToppings.join(',');
  },
  // ...
});
And if I bind this variable into the template inside the same tag as my list model attribute:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>
{{pizzaState}}
{{model.firstHalfToppings}}
{{model.secondHalfToppings}}</pre>
    <!-- ... -->
  </template>
  <script src="x_pizza.js"></script>
</polymer-element>
Then, not only is the new bound variable updated in the template each time that method is called, but the list model attribute is also updated:



So it seems that the Dart version was behaving correctly. Or at least consistently.

The last thing that I try tonight is observing the list properties of the model. If nothing else, I would like to have single place to accumulate changes. This turns out to be fairly easy with Polymer's observe property:
Polymer('x-pizza', {
  ready: function() {
    this.model = {
      firstHalfToppings: [],
      secondHalfToppings: []
    };
  },
  observe: {
    'model.firstHalfToppings': 'updatePizzaState',
    'model.secondHalfToppings': 'updatePizzaState'
  },
  updatePizzaState: function() {
    this.pizzaState = this.model.firstHalfToppings.join(',') + "\n" +
      this.model.secondHalfToppings.join(',');
  },
  // ...
});
The path expressions that serve as keys in the observe property establish change listeners for the specified properties. Polymer is able to resolve those strings into objects and properties, listening to the appropriate event source for a change. And, when a change does occur, the updatePizzaStat method is invoked.

That works just fine. I think I am fairly close to fully understanding this approach and how Polymer wants it done. I may switch back to Polymer tomorrow to make certain.


Day #996

Monday, January 13, 2014

Day 995: Observing Model Attributes in Polymer


As of last night, I have a nifty little pizza builder Polymer:



OK, so maybe not that nifty, but it was pretty easy to slap together. It is also fairly well-factored, slapped-together code, by virtue of a separate model that describes the internal state of the pizza. There is still room for improvement, however, as I would like for the model to be able to signal to the Polymer (or anything else for that matter) that its internal state has changed.

Currently, when the user adds an ingredient to the pizza, each of the various add-ingredient methods need to tell the main UI element to re-draw itself:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  addFirstHalf() {
    model.firstHalfToppings.add(currentFirstHalf);
    pizzaState = model.toString();
  }
  // ...
}
That's not horrible except each one of the add-ingredient methods needs to update the value of pizzaState in exactly the same way so that it is available in the template:
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>{{pizzaState}}</pre>
    <!-- ... -->
  </template>
  <script type="application/dart" src="x_pizza.dart"></script>
</polymer-element>
But there must be a better way to communicate that information, right?

The approach that I take is making the various properties in the Pizza class @observable:
class Pizza {
  @observable List<String> firstHalfToppings = toObservable([]);
  // ...
}
Back in the main Polymer element, I mark the Pizza model as @observable as well:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  @published Pizza model;
  // ...
  addFirstHalf() {
    model.firstHalfToppings.add(currentFirstHalf);
  }
  // ...
}
I also remove the duplicated pizzaState setting.

To get this to work, I have to listen to the model's attribute:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  @published Pizza model;
  XPizza.created(): super.created() {
    model.firstHalfToppings.changes.listen((records) {
      pizzaState = model.toString();
      print('changed: $records');
      print(model.toString());
    });
  }
  // ...
}
Listening to the model itself is not sufficient as it does not see changes from its own properties.

Interestingly, or should I say frustratingly, I cannot bind template variables to the model's properties:
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>
{{model.firstHalfToppings}}
{{model.secondHalfToppings}}</pre>
  </template>
  <script type="application/dart" src="x_pizza.dart"></script>
</polymer-element>
They show the initial value of an empty list, but never update. What is especially frustrating is that, if I include pizzaState in addition to those bound model attributes, then it works:
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>
{{pizzaState}}
{{model.firstHalfToppings}}
{{model.secondHalfToppings}}</pre>
  </template>
  <script type="application/dart" src="x_pizza.dart"></script>
</polymer-element>
The simple inclusion of that Polymer attribute results in both it being updated as well as the model attributes:



And I am not sure why. I think it may be time to take a break to get more familiar with model driven views in JavaScript tomorrow. After that, hopefully, I will have a better idea how to do this in Dart.


Day #995

Sunday, January 12, 2014

Day 994: Stay Classy with Polymer Models


There are two good ways to learn something new: flail around making dumb mistakes and reading smarter people's words and code. Naturally, I prefer the former.

In all seriousness, I find it easier to internalize how a language or tool wants me to work if I struggle to make it work the way I think it should. Usually I can learn a thing or two about my subject of study and I inevitably get exposed to smarter people's work while I figure out why my approach does not work. It might seems counter-intuitive, but really, making mistakes—the worse the better—really works well as I learn.

But tonight, I try the opposite. I have been working against Polymer long enough. It is time that I tried a trick of two that I have picked up along the way. I start with the “model pattern,” for lack of a better name. Actually a better name might simply be the strategy pattern because that is what it really is. But I keep calling it the model pattern when I come across others doing it in Polymer mostly because there is always a model attribute on the Polymer.

I don't know why, but I find that real classy. I want to be classy too. And what's more classy that order pizza? So I am going to build an <x-pizza> element that can build a pizza for order.

I start a new web application with a Dart Pub pubspec.yaml that pulls in Polymer.dart:
name: model_example
dependencies:
  polymer: any
dev_dependencies:
  unittest: any
transformers:
- polymer:
    entry_points: web/index.html
I start a pizza building homepage to smoke test my model pattern Polymer. I create it as web/index.html:
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Pizza Maker</title>
    <!-- Load component(s) -->
    <link rel="import" href="packages/model_example/elements/x-pizza.html">
    <!-- Load Polymer -->
    <script type="application/dart">
      export 'package:polymer/init.dart';
    </script>
  </head>
  <body>
    <div class="container">
      <h1>Dart Bros. Pizza Builder</h1>
      <x-pizza></x-pizza>
    </div>
  </body>
</html>
That is almost boilerplate at this point. I pull in the Polymer definition and the Polymer.dart platform at top. Then I use the <x-pizza> element below.

Similarly, the <x-pizza> definition is fairly straight-forward. I create lib/elements/x-pizza.html as:
<polymer-element name="x-pizza">
  <template>
    <h2>Build Your Pizza</h2>
    <pre>{{pizzaState}}</pre>
    <p>
      <select class="form-control" value="{{currentFirstHalf}}">
        <option>Choose an ingredient...</option>
        <option value="{{ingredient}}" template repeat="{{ingredient in ingredients}}">
          {{ingredient}}
        </option>
      </select>
      <button on-click="{{addFirstHalf}}" type="button" class="btn btn-default">
        Add First Half Topping
      </button>
    </p>
    <!-- ... -->
  </template>
  <script type="application/dart" src="x_pizza.dart"></script>
</polymer-element>
That is just variable binding in templates.

The bulk of the work comes in the backing class, which needs a Pizza class:
class Pizza {
  List<String> firstHalfToppings = [];
  List<String> secondHalfToppings = [];
  List<String> wholeToppings = [];
  toString()=> """First Half: $firstHalfToppings
Second Half: $secondHalfToppings
Whole: $wholeToppings""";
}
To use that as a model, I need only define an instance variable cleverly named “model” and assign an instance of Pizza to it:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  final bool applyAuthorStyles = true;
  final List ingredients = [
    'pepperoni',
    'sausage',
    'green peppers'
  ];

  @observable String currentFirstHalf = 'Choose an ingredient...';
  // ...
  @observable String pizzaState;

  Pizza model = new Pizza();

  XPizza.created(): super.created();
}
All that is needed at this point is to use the model, which I do in the various add-toppings bound methods:
@CustomTag('x-pizza')
class XPizza extends PolymerElement {
  // ...
  addFirstHalf() {
    model.firstHalfToppings.add(currentFirstHalf);
    pizzaState = model.toString();
  }
  // ...
}
And that does the trick:



That is not quite the end of the story, however. I should be able to make the model itself observable so that, when its internal state is updated, it can trigger the update to the value displayed to the hungry buyer. I will leave that for another day. For now, I am happy just being on the way to classiness.


Day #994

Saturday, January 11, 2014

Day 993: Vulcanize (with Exclusions)


Deployment of Polymer.dart is causing me a bit of bother. In a good way. I continue to stretch the boundaries of what Polymer can do—and probably should do. I have to admit that I am struggling with including data in Polymers—especially when it comes to deployment. I am so very close to having a working solution in Dart, but I begin to suspect that I am fighting the framework just a little too much. So I am switching apps, back to the JavaScript equivalent to see if I have similar problems.

I am still trying to read configuration from both the Polymer definition and when using the Polymer. I have been placing the configuration in a <link> import before the Polymer definition:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="hello-you.json">
<polymer-element name="hello-you">
  <!-- ... -->
</polymer-element>
The configuration when using the element goes inside the Polymer tags:
<hello-you>
  <link rel="import" href="scripts/hello-you.json">
  <p>And good-bye…</p>
</hello-you>
And, thanks to the magic of Polymer, that works just fine—when the Polymers are separate from the web and not combined into a single deployment asset. But I recognize that this might not be ideal for real-world usage, which is where the deployment-minded vulcanize comes in.

I start by installing vulcanize:
$ npm install -g vulcanize
Then I run it on the entry page to my JavaScript Polymer application:
$ vulcanize index.html
Default output to vulcanized.html in the input directory.
When I look at my JSON configured Polymer pre-vulcanize, I see:



When I load up the vulcanized version, I find:



Well, that does not bode well for my attempts at external configuration.

There are a couple of options that vulcanize supports. The --csp creates an external JavaScript file, but my configuration imports are still slurped directly into the page.

The only other option that I can think to use is the --config. In a configuration file, I find that I can specify imports that I want vulcanize to ignore. That sounds promising. So I create vulcanize_conf.js with the following content:
{
  "excludes": {
    "imports": [
      "\\.json$"
    ]
  }
}
The documentation suggests that I can exclude by regular expression, which is what I do above. I then use the configuration:
$ vulcanize --config=vulcanize_conf.js index.html 
Default output to vulcanized.html in the input directory.
And that actually works:



Well, not quite. The default configuration in the Polymer definition is still imported, but the configuration when I use the Polymer, while still in the HTML, is not imported properly.

Still, this seems promising. While not ideal to have to exclude JSON configuration in Polymers, it seems doable and seems, if anything, slightly easier than in the Dart equivalent.



Day #993

Friday, January 10, 2014

Day 992: Search and Replace Dart Transformer to Hide from Polymer


OK I lied. Yesterday, I breezed past a little Dart problem in an effort to finish off some work. Today I try to address that oversight.

As I briefly mentioned yesterday, I am able to read Polymer configuration that is stored <link> imports inside the definition of a Dart Polymer:
<script src="../../packages/browser/dart.js"></script>
<script src="../../packages/browser/interop.js"></script>
<polymer-element name="hello-you">
  <link rel="import" href="hello-you.json">
  <template>
    <!-- ... -->
  </template>
  <script type="application/dart" src="hello_you.dart"></script>
</polymer-element>
It takes a little effort, but I can grab hello-you.json from the Polymer, reading the data into the Polymer's configuration data. I have to work through the declaration property and run the result through a transformer, but it is doable.

What I cannot quite do is <link> import data when I use the Polymer:
<hello-you>
  <link rel="import" href="hello-you.json">
  <p>And good-bye…</p>
</hello-you>
My problem is something of a running theme with Polymer.dart—the deployment transformer includes <link> imports inline, which results in actually seeing the JSON data embedded diring in the web page:



I can work around this inside the Polymer definition with a deployment build transformer that searched for raw JSON, wrapping it in a display: none styled tag. The actual <link> tag remains in the Polymer, allowing me to read it as configuration.

My problem with configuration in a Polymer is twofold. First, it is a little harder to find the JSON to wrap it inside display: none tags. Second, even if I could do so, the <link> tag is stripped out so that I could not read it even if I wanted to do so. I end up with this in the main web page:
{
  "hello": "Yo"
}
<div class="container">
  <hello-you>
    
    <p>And good-bye…</p>
  </hello-you>
</div>
I think the best thing would be to pre-transform the page so that, by the time the Polymer transformer sees it, it is no longer a <link>. The pre-transformer could take the Polymer:
<hello-you>
  <link rel="import" href="hello-you.json">
  <p>And good-bye…</p>
</hello-you>
And transform it to:
<hello-you>
  <!-- link rel="import" href="hello-you.json" -->
  <p>And good-bye…</p>
</hello-you>
Then the code could pass through the Polymer transformer, which can do its usual thing—except that it will skip the commented <link> tag. Finally, a post-transformer could restore the original <link>:
<hello-you>
  <link rel="import" href="hello-you.json">
  <p>And good-bye…</p>
</hello-you>
I have gotten pretty good at writing search and replace Dart Pub transformers. So good, in fact, that I think it is time to write a pub package. If I call the package replace_transformer, then my application could have a pubspec.yaml that looks like:
name: config_example
dependencies:
  polymer: any
  replace_transformer:
    path: /home/chris/repos/replace_transformer
dev_dependencies:
  unittest: any
transformers:
- replace_transformer:
    file: web/index.html
    match: '<link rel="import" href="hello-you.json">'
    replace: '<!-- link rel="import" href="hello-you.json" -->'
- polymer:
    entry_points: web/index.html
- replace_transformer:
    file: web/index.html
    match: '<!-- link rel="import" href="hello-you.json" -->'
    replace: '<link rel="import" href="hello-you.json">'
In the dependencies section of pubspec.yaml, I mark my new replace_transformer package as a dependency. Once I am ready to release this package to pub.dartlang.org, I will remove the local path. For now, the local path allows me to build my transformer and try it right away. Brilliant!

There are two ways to name a Dart transformer and I have forgotten one of them. The one I do remember is to create a file named transformer.dart. So in replace_transformer, I create lib/transformer:
library replace.transformer;
import 'dart:async';
import 'package:barback/barback.dart';

class ReplaceTransformer extends Transformer {
  String file;
  Pattern match;
  String replace;

  ReplaceTransformer(this.file, this.match, this.replace);

  Future isPrimary(Asset input) { /* ... */ }

  Future apply(Transform transform) { /* ... */ }
}
Nothing out of the ordinary there. I declare a library. I import packages—async for access to Future and barback from pub itself for the Transformer class as well as the ability to read the pubspec.yaml configuration. I declare the three instance variables that will be assigned from pubspec.yaml and define a constructor that assigns those instance variables. Lastly, I define the two methods that need to be implemented by a subclass of Transformer. The isPrimary() method indicates if a particular asset needs to be directly transformed (it will have to return true when the asset matches file). And the apply() method actually performs the transformation.

Pub expects its tranformers to define an asPlugin named constructor which access barback settings:
class ReplaceTransformer extends Transformer {
  String file;
  Pattern match;
  String replace;

  ReplaceTransformer(this.file, this.match, this.replace);

  ReplaceTransformer.fromList(List a): this(a[0], a[1], a[2]);

  ReplaceTransformer.asPlugin(BarbackSettings settings)
    : this.fromList(_parseSettings(settings));
  // ...
}
I redirect this constructor to the fromList() named constructor that takes a list and redirects to the primary constructor with the three expected values. The _parsedSettings() is easy enough:
List<String> _parseSettings(BarbackSettings settings) {
  var args = settings.configuration;
  return [
    args['file'],
    args['match'],
    args['replace']
  ];
}
With that, I need to teach my ReplaceTransfomer when to apply transforms:
  Future<bool> isPrimary(Asset input) {
    if (file == input.id.path) return new Future.value(true);
    return new Future.value(false);
  }
And I need to replace all instances of match with replace when the transform is applied:
  Future apply(Transform transform) {
    var input = transform.primaryInput;
    return transform.
      readInputAsString(input.id).
      then((html){
        var fixed = html.replaceAllMapped(
          match,
          (m) => replace
        );

        transform.addOutput(new Asset.fromString(input.id, fixed));
      });
  }
And that actually does the trick. Now when I load my Polymer, the <link> tag makes it through Polymer's transformer unscathed:



Nice! I am still a little uncertain how to approach this stuff in Patterns in Polymer, especially since the JavaScript version of Polymer does not really have the concept of asset packaging. But, for now, I am glad to feel like I have a workable, if a bit verbose solution in Dart.

Day #992

Thursday, January 9, 2014

Day 991: Mixing Config and Content in Polymers


So it turns out that I already know how to do the rest. I hate it when that happens.

The whole point of these posts is to ask a question to which I don't know the answer—and then answer it (or come up with next steps). So first the answer to the question I did not remember knowing. Then a new question that I am pretty sure I don't know.

First up: how to mix distributed content with imported configuration in Polymer? The answer: you just do it. For instance, if I wanted to distribute “And good-bye…” as closing content in my super-simple <hello-you> Polymer, I can write it like:
      <hello-you>
        <link rel="import" href="scripts/hello-you.json">
        <p>And good-bye…</p>
      </hello-you>
Now I am importing hello-you.json configuration and including HTML content inside my custom <hello-you> Polymer instead of just using configuration. I can continue to use the same code to process the configuration from yesterday without change. To include the HTML content—without <link> noise, I just include a <content> tag like usual in the Polymer's <template>:
<link rel="import" href="../bower_components/polymer/polymer.html">
<polymer-element name="hello-you">
  <template>
    <h2>{{hello}} {{your_name}}</h2>
    <!-- ... -->
    <content></content>
  </template>
  <script>
    Polymer('hello-you', {
      // ...
    });
  </script>
</polymer-element>
The result is exactly what I desire—the content wrapped by my Polymer is distributed into the Polymer's DOM:



I already know how to do similar stuff in Dart. Instead of importing outside of the <polymer-element> tag, I need to include the <link> tag inside:
<script src="../../packages/browser/dart.js"></script>
<script src="../../packages/browser/interop.js"></script>
<polymer-element name="hello-you">
  <link rel="import" href="hello-you.json">
  <template>
    <!-- ... -->
  </template>
  <script type="application/dart" src="hello_you.dart"></script>
</polymer-element>
I also have to use my Polymer transformer to strip out JSON, but I have gotten used to that.

What I need to figure out tonight, is how to organize my Polymers. I have been putting everything in a scripts directory and, especially with all of the internal and external configuration floating around, that seems to be messy.

Folks have suggested an “elements” directory to hold Polymers. And after a bit of fiddling, I settle on that as well. It is not as tied to implementation as “polymers” might be, but seems to do a good job of separating regular code from Polymer:
$ tree -I 'bower_components|node_modules'
.
├── assets
│   └── bootstrap.min.css
├── bower.json
├── elements
│   ├── hello-you.html
│   └── hello-you.json
├── Gruntfile.js
├── index.html
├── karma.conf.js
├── package.json
└── scripts
    └── hello-you.json
Here, the hello-you.json in the scripts directory is the custom configuration that is being applied to the Polymer whereas the one inside elements is the internal configuration for the Polymer.

I am still unsure if it really helps much in the Dart code. The custom configuration there tends to reside in the web directory and everything else—Polymer and Polymer backing code—goes in lib. Still some folks seem to prefer placing elements in lib/elements and that seems more consistent between the two languages so I will probably adopt that convention as well.

Day #991

Wednesday, January 8, 2014

Day 990: Internal Configuration of Polymers


The line between configuration and attributes is a fine one. For Polymer elements I offer the number 6 as the dividing line. If a Polymer supports more than 6 attributes, then it seems ugly to jam them into a list of HTML attributes.

Even when configuration is used, defaults can reside in the Polymer definition as attributes:
    Polymer('hello-you', {
      hello: 'Hello',
      done: 'Done',
      instructions: 'Introduce yourself for an amazing personalized experience!',
      // ...
    });
That will work just fine even if the Polymer supports importing external configuration as I established last night in form of <link> imports:
      <hello-you>
        <link rel="import" href="scripts/hello-you.json">
      </hello-you>
But I like the idea of using the same configuration file internally in the Polymer as is supported when using the Polymer. To do that, I can use a similar <link> import trick, only the access is slightly different than last night.

First things first, I include the internal configuration in the same place that I include the Polymer library itself—outside of the <polymer-element> definition:
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="_hello-you.json">
<polymer-element name="hello-you">
  <template>
    <!-- ... -->
  </template>
  <script>
    Polymer('hello-you', {
      // ...
    });
  </script>
</polymer-element>
Now, inside the Polymer class, I can load the internal configuration before the external configuration, which allows the external configuration, if specified, to take precedence:
    Polymer('hello-you', {
      // ...
      ready: function() {
        this._loadConfig();
        this._loadCustomConfig();
      },
      // ...
    });
As for reading the internal _hello-you.html configuration file, I figured out how to do that when I was mucking around with internationalization. I can query for the <link> tags in the Polymer definition through the element property:
    Polymer('hello-you', {
      // ...
      ready: function() {
        this._loadConfig();
        this._loadCustomConfig();
      },

      _loadConfig: function() {
        var links = this.
          element.
          parentElement.
          querySelectorAll('link[rel=import]').
          array().
          filter(function(el) {
            return el.href.match(/_hello-you.json/)
          });

        if (!links.length) return;

        var json = links[0].import.textContent.replace(/import/, '');
        var config = JSON.parse(json);

        for (var prop in config) {
          this[prop] = config[prop];
        }
      },
      // ...
    });
The only trick remains to remove the work “import” from the <link> tag's text content.

With that, I have an internal configuration for my Polymer. If I define the default, internal configuration in _hello-you.json as:
{
  "hello": "[Default] Hello",
  "done": "[Default] Done",
  "instructions": "[Default] Introduce yourself for an amazing personalized experience!"
}

Then my Polymer, in lieu of a custom configuration, looks like:



If I add a custom configuration when I use the Polymer:
      <hello-you>
        <link rel="import" href="scripts/hello-you.json">
      </hello-you>
Then I get my customized Polymer:



This small example file is probably overkill for configuration. As I said, the dividing line is probably somewhere around 6 attributes that would need to go in the configuration JSON file. But this seems to work nicely. There are still a few questions left to answer, but this vein of exploration continues to look promising. I will pick back up tomorrow night to see if the external configuration will work even when I want to use the <content> tag to distribute content.


Day #990