Polymer.dart: Programatically create template bindings

In a previous article, we have seen how to create bindings without using custom elements. It is also possible to add dynamic template bindings programmatically from the dart code.

We will use the same model class we used in the previous article.

We won’t need any template code for this example. Instead we will do it programmatically from the dart code.

Notice the use of content member of TemplateElement class. It provides access to the DocumentFrament of the template. It is important to set the bind attribute on template element.

Polymer.dart: Create polymer expressions/bindings without using custom elements

Creating custom elements is fun, simple and modular. But there are times when you don’t need custom component. If you feel this need, this article is for you. In my case, I wanted one-way binding that can be added dynamically to the dom.

We can do the bindings without creating a custom element using a sub-package of Polymer called polymer_expression.

Add the following dependencies to pubspec.yaml

  • polymer_expression
  • observe

Add the following to your html page

Notice the template tag and its attribute bind. The polymer expression {{count.count}} will change when it is changed in the code.

We will use observe package to notify any changes to the models we create.

Create model class for the counter

Add the following code to your dart code

The globals map contains all the mappings for use in the template binding. The function templateBind provides access to the binding API(TemplateBindExtension). bindingDelegate and model members of TemplateBindExtension can be used to specify required global binding delegate and model respectively. In the above example, we have seen the use of global binding delegate. In the following example, we will see how we can bind a specific model to a template.

Lets use the same model we used in the previous example. This is the dart code to bind a specific model to a template.

Notice the use of model member of TemplateBindExtension. Now lets see the changes to the template code

As you can see, since we have binded a specific model to the template, we have access to the members of the model directly without having to go through the entire hierarchy.

Ofcourse you can use both binding delegate and model on the same instance of a template.