2012-09-24 55 views
1

我不知道是否可以這樣做,但我有這個JSON結構:發送JSON數據基於數據對象數組不同的車把模板

var data = {"obj": [ 
       {"user": "Fred", "age": "23", "type": "personal"}, 
       {"user": "Ralph", "age": "32", "type": "business"}, 
       {"user": "John", "age": "44", "type": "other"} 
      ] 
      }; 

我有我的HTML頁面,3個目標區域我想根據「類型」顯示用戶和年齡。我使用的把手使這些在我的阿賈克斯這樣的:

var source, 
template = Handlebars.compile(source), 
data; 

$.each(data['obj'], function (i, o) { 
    if (o['type'] === "personal") { 
     source = $("#personal").html(); 
     $("#place1").html(template(data)); 
    } else if (o['type'] === "business") { 
     source = $("#business").html(); 
     $("#place2").html(template(data)); 
    } else if (o['type'] === "casual") { 
     source = $("#other").html(); 
     $("#place3").html(template(data)); 
    } 
}); 

我希望把它使得$。每個函數將每個對象數組發送到指定的地方,但他們最終只是將批次發送到一個部分,然後發送下一個部分等等。請幫忙!

回答

1

你快到了。編譯模板函數,template你的情況,需要一個對象作爲參數,所以你可以說:

$('#place1').html(template(o)); 

,然後模板將使用{{user}}{{age}}訪問數據;例如:

{{user}}'s age is {{age}} 

如果你想改變爲每種類型的實際的模板,然後再打電話Handlebars.compile

if(o.type === 'personal') { 
    template = Handlebars.compile($('#personal').html()); 
    $('#place1').html(template(o)); 
} 

您可以緩存編譯模板中的對象,如果你想要的。

+0

源代碼更改後不應該重新編譯模板嗎? – balafi

+0

@Elias:你的意思就像我更新的答案? –

+0

是的。謝謝。 – balafi