this.data in jQuery tmpl
Anatoly Mironov
In jQuery tmpl we can render properties with {{= SomeProperty }}. Here is an example:
<script type="text/javascript">
Writer = function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Writer.prototype = {
getFullName: function () {
return this.firstName + " " + this.lastName;
}
};
$(document).ready(function () {
var writers = \[\];
writers.push(new Writer("Gennady", "Ajgi"));
writers.push(new Writer("Mišši", "Şeşpĕl"));
writers.push(new Writer("Ille", "Tuktaš"));
writers.push(new Writer("Kĕştenttin", "Ivanov"));
$("#tmpl").tmpl(writers).appendTo("#writers");
});
</script>
<script id="tmpl" type="text/html">
<li>
{{= firstName }} {{= lastName }}
</li>
</script>
<div id="writers"></div>It will render like:
- Gennady Ajgi
- Mišši Şeşpĕl
- Ille Tuktaš
- Kĕştenttin Ivanov
But what if we want to access the object itself, not one of the properties. Say, you want to pass the object from the array into a js function as a parameter to decide how it will be rendered, or if you want show a “calculated” property. The key word is…: this.data. this.data has the current object. After it has been rendered, we can access this object with $(this).tmplItem().data.
<script type="text/javascript">
Writer = function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Writer.prototype = {
getFullName: function () {
return this.firstName + " " + this.lastName;
}
};
$(document).ready(function () {
var writers = \[\];
writers.push(new Writer("Gennady", "Ajgi"));
writers.push(new Writer("Mišši", "Şeşpĕl"));
writers.push(new Writer("Ille", "Tuktaš"));
writers.push(new Writer("Kĕştenttin", "Ivanov"));
$("#tmpl").tmpl(writers).appendTo("#writers");
});
</script>
<script id="tmpl" type="text/html">
<li>
{{= this.data.getFullName() }}
</li>
</script>
<div id="writers"></div>The cool thing is, you don’t even need to pass this.data as parameter to a function for processing, you can invoke your function without parameters. Inside this function you have access to this.data. So if you had created a normal function getFullName without a prototype:
function getFullName(person) {
return person.firstName + " " + person.lastName;
}So you could just invoke this from template like {{= getFullName }}. But it becames loose. So I wouldn’t recommend it. The prototype way is a better way to structure it.