views:

98

answers:

2

Using this as the example: http://mustache.github.com/#demo, the template and json can functionally be moved to a var:

template = '<h1>{{header}}</h1>{{#items}}{{#first}}<li><strong>{{name}}</strong></li> {{/first}}{{#link}} <li><a href="{{url}}">{{name}}</a></li> {{/link}}{{/items}}{{#empty}} <p>The list is empty.</p>{{/empty}}';

This is where things break down:

$.ajax({
    url: "must_template.js",
    dataType: "html",
    success: function(data) {
    template = data;
    }
});

and

$.ajax({
url: "theJson2.txt",
dataType: "json",
success: function(data) {
        json = data;
        //json = $.parseJSON(data);
    }
});

Chrome's console shows exactly the same content as the var, but Mustache breaks on the inputs because they're "Undefined" on input:

Uncaught TypeError: Cannot call method 'indexOf' of Undefined

I've tried changing the dataType, parsing it using $.parseJSON and nothing works when importing either the template or JSON from an external file.

If there are any tips for troubleshooting javascript objects, that would be appreciated as well.

Update: Code is here: http://dev.plitto.com/sandbox/mustache_riff/index4.html theJson.txt is the JSON. It's being pulled correctly. console.log(data.header) correctly returns. must_template.js is the Mustache template file (pulling externally will allow for different themes).

A: 

What is the difference between the two? And what are in theJson2.txt and must_template.js?

Parse JSON with:

data = JSON.parse(data);

And to see what's in the object, use Firebug or the JS Console in Safari / Chrome with:

console.log(data);

If you get some more information up we can be more help :)

jamie-wilson
A: 

Turns out this is a scope problem.

The template variable is defined before the $.ajax() call, and the value is only valid within the $.ajax call.

Ben Guthrie
This was the code that fixed it: json = $.ajax({ url: "theJson.txt", dataType: "json", async: false }).responseText;
Ben Guthrie