-
Notifications
You must be signed in to change notification settings - Fork 69
Using data bind for Clean Plating
mwawrusch edited this page Nov 25, 2011
·
8 revisions
In plates you have several methods that can be used for templating. You can use the id (note though that id's have to be unique in the DOM), you can use class names, and you can use your own tags. If you use your own tags you will want to use data-* as it is part of HTML5, and this page explains how you can do it in plates.
First of all, you are free to use whatever syntax you like, plates does not discriminate. That said there are some practical advantages to use the following syntax.
- Use data-bind="Name of field in data source" to bind to the content of the tag.
- Use data-bind-[attr]="Name of field in data source" where [attr] is something like src, href, value to bind to a specific attribute in the html.
- Easy search. You can search your entire project for data-bind and data-bind-* to find all data bound elements. That is tremendously valuable in larger projects.
- You communicate intent well. Every developer grasps what data-bind means. Using a class name does not indicate that binding takes place.
- You can tell your designers to ignore data-bind. They will mess with classes (they just can't help themselves) but you can educate them that data-binds are not to be fooled around with.
- data-bind can be easily used for two-way binding, the process of binding html content to a data object.
- A tad bit more typing.
- You need a map structure. Note that this could be optimized in a very smart way with some javascript.
Note: there is still a little bug in plates that prevents 2 replacements in one tag, but that will be fixed soon.
Create a html like so:
<p data-bind="para"></p>
<input type="text" data-bind-value="name" data-bind-placeholder="placeholder"></input>
A data like so
var data = { "name" : "Frank", "placeholder" : "Some dude", "para" :"Some Paragraph" };
A map like so
var map = {"name" : ["data-bind-value", "value"] ,
"para" : ["data-bind"],
"placeholder" : ["data-bind-placeholder", "placeholder"] };
What the map file says is basically this:
- If you encounter a para field in your data, then look for a data-bind tag in the template html, and if you find it replace the contents of the tag with the value "Some Paragraph". Note that the second parameter in the map array for para is undefined/null. That forces mapping into the content of the tag, instead of an attribute.
- If you encounter a name field in your data, then look for a data-bind-value tag in the template html, and if you find it replace the value attribute with "Frank"
- If you encounter a placeholder field in your data, then look for a data-bind-placeholder tag and replace the placeholder attr with "Some Dude"
which results in this:
<p>Some Paragraph</p>
<input type="text" data-bind-value="name" data-bind-placeholder="placeholder"
value="Frank" placeholder="Some dude"></input>