I’m working with backbone and lazy-loading both templates and data for one of my views. For “simplicity” (in terms of not having to do multiple asynchronous server calls), I’m attempting to load both from the same file persons.php, which returns something like this:
<script type='text/template' id='persons-template'>
<div><%= name %></div>
</script>
<script type='text/javascript'>
var persons: [
{ name: "some dude" },
{ name: "some other dude" }
];
</script>
The view itself is loading this file using an Ajax call, and attempting to parse, like so:
var self = this;
$.get("persons.php").function(data) {
self.template = _.template($(data).html());
self.model = new PersonsCollection;
// problem here: persons is undefined
self.model.reset(persons);
self.render();
});
So, persons is undefined. I know why: the script block is not added to the DOM. I can use $(data)[1] to get an HtmlScriptElement; using $($(data)[1]).text() gives me the Javascript as a string like this:
“var persons: [ { name: “some dude” }, { name: “some other dude” } ];”
How can I access the persons object so that I can pass it to my model?
Take any returned scripts with no type, or type
'text/javascript', and stuff it into the DOM before templating.