views:

44

answers:

2

Hey!

The following code:

jQuery(document).ready(function($) {
    function getBooks() {
        var query = "ajax.php?do=allbooks";
            $.ajax({
                dataType: "jsonp",
                url: query,
                jsonp: "callback",
                success: showBooks
            });
    }

    function showBooks(data) {
    $("#bookTmpl").tmpl(data, { 
        getName: function() {
          return 'bla';
        }
    }).appendTo( "#test" ); 
    }

    getBooks();
});

What I am trying to do is use the getName()-function in my template.

Let's pretend my template looks like this:

<script id="bookTmpl" type="text/x-jquery-tmpl">
    <li>
    ${title} by ${author}<br />
    Rating: ${rating} -> ${getName()}
    </li>
</script>

What do I have to change to make it work? Right now, the function isn't even executed. Everything else works.

+1  A: 

Try attaching the error: fn callback in $.ajax and see what might be wrong. Perhaps the JSON is malformed (you can check that with jsonlint.org). If the success: fn isn't even being called, something is wrong (404, JSON parse error etc.).

Also, JSONP might be a bit overkill if you're requesting JSON from the same domain (e.g. try something like $.getJSON or dataType: 'json')

peol
Sorry, I somewhat misread your question. Does your template work (except for the method)?
peol
Yes, the template works. :-)
dHahn
+3  A: 

You just need to adjust the call a bit, change this:

${getName()}

To this:

${this.getName()}

You can test it out here.

Nick Craver