无法从Backbone处理JSON的手柄模板

无法从Backbone处理JSON的手柄模板

问题描述:

Handlebars无法读取我将其作为上下文发送的JSON对象。无法从Backbone处理JSON的手柄模板

下面是使调用胡子模板,并赋予它的背景功能:

render: function() { 
    var source = $("#round").html(); 
    var template = Handlebars.compile(source); 
    var context = JSON.stringify(this.model); 
    console.log(context); 
    var html = template(context); 
    $(this.el).html(html); 
    return this; 
}, 

下面是我通过它的JSON对象:

{"result":0,"friend1":{"firstName":"Ape","lastName":"Head","fbID":329018,"kScore":99,"profilePic":""},"friend2":{"firstName":"Ape","lastName":"Hands","fbID":32,"kScore":70,"profilePic":""}} 

这里是把手模板:

<script id="round" type="text/x-handlebars-template"> 
    {{#with friend1}} 
    <h2>{{firstName}} {{lastName}}</h2> 
    {{/with}} 
    </script> 

我收到以下错误:

Uncaught TypeError: Cannot read property 'firstName' of undefined 

替换此功能:

render: function() { 
    var source = $("#round").html(); 
    var template = Handlebars.compile(source); 
    var context = JSON.stringify(this.model); 
    console.log(context); 
    var html = template(context); 
    $(this.el).html(html); 
    return this; 
}, 

与:

render: function() { 
    var source = $("#round").html(); 
    var template = Handlebars.compile(source); 
    var context = JSON.parse(this.model.toJSON); 
    console.log(context); 
    var html = template(context); 
    $(this.el).html(html); 
    return this; 
}, 

template应该采取javascript对象在这种情况下。 JSON.stringify返回JSON对象的字符串表示形式,而不是JavaScript对象。但是你真正想要的是模型的属性。所以你可以通过toJSON或者JSON.stringify(this.model)来访问它们,但是你需要把它们转换回一个Javascript对象。

+0

嗯,它似乎没有工作。 “this.model”是一个Backbone对象,这就是为什么我将模板传递给JSON字符串的原因。 – egidra

+1

这可能看起来很奇怪,但试试:'JSON.parse(JSON.stringify(this.model))' – Joe

+0

啊,这工作! – egidra

尝试:

var html = template(this.attributes); 

骨干模型对象的attributes属性包含所述数据的JS对象表示。直接访问它并不是很好的做法,但在这种情况下,它可能是最简单的事情,而不是试图通过JSON来回传数据。

我不得不同意丹的回答,以最快的方式做到这一点。 在名单的情况下,您可能需要的ID来捕获点击,你甚至可以做到这一点

<script id="round" type="text/x-handlebars-template"> 
{{#each friends}} 
<li id="{{ this.id }}" >{{this.attributes.firstName}} {{this.attributes.lastName}}</li> 
{{/each}} 
</script> 

在模板调用只需使用.toJSON(),这将改变模型属性由车把预期JSON对象:

template(this.model.toJSON());