Search code examples
javascriptjqueryjquery-templates

How to create a compound property and use it in a jQuery template?


I'd like to be able to create a JS object that has a field that combines existing fields in the object together, but I think I have a context problem for "this" that I'm not sure how to solve.

Here's what I'm trying to do:

function Person(firstName, lastName)
{
    this.FirstName = firstName;
    this.LastName  = lastName;

    this.FullName = function ()
    {
        return this.FirstName + " " + this.LastName;
    }
}

I wish to use FullName is a jquery Template, but haven't had luck.

<script type="text/x-jquery-tmpl" id="tmplImg">
    {{each people}}
        <li>
            ${FullName}
        </li>
    {{/each}}
</script>

I think it can be done somehow because the knockout.js library is able to accomplish it somehow as shown in this tutorial (Step 4).

http://learn.knockoutjs.com/#/?tutorial=templates


Solution

  • Working Demo:

    function Person(firstName, lastName) {
        this.FirstName = firstName;
        this.LastName = lastName;
        var self = this;
        this.FullName = function() {
            return self.FirstName + ' ' + self.LastName;
        }
    }