2
(編輯瞭解更多信息)Backbone.js - 從JSON文件獲取特定值
我在Backbone.js中創建了一個Pizza Builder應用程序。現在我想要的是什麼時候點擊了一個特定的模型(用e.currentTarget()來做到這一點);我想從該模型的描述追加到不同的分步div。
所有的數據都是在Successhandler中獲取的,但我不知道如何獲取特定成分的具體描述。我希望有人能幫助我。
**Ingredient Model**
site.models.Ingredient = Backbone.Model.extend({
defaults: {
"name": 'Ingredient',
"sort": 'None',
"description": "Default",
"price": 0,
"bake-time": 0,
"vegetable": ""
}});
**Ingredient Collection**
site.collections.IngredientCollection = Backbone.Collection.extend({
model: site.models.Ingredient,
url: "js/Ingredients.json"});
**Ingredient View**
site.views.Ingredient = Backbone.View.extend({
description: '',
price: '',
events: {
"click p": "ingredientClicked" //Call ingredientClicked function
},
initialize: function(getInfo){
this.ingredientTemplate = getInfo.ingredientTemplate;
this.getIngredients(); //Load the Ingredients Function
},
//Call a handler when an ingredient is clicked!
ingredientClicked: function(e){
var chosenIngredient = $(e.currentTarget).data('ingredient'); //Get Current Target (Name that's clicked)
console.log(this.appendIngredient);
console.log(chosenIngredient);
$("#ingredients").append("<li>" + chosenIngredient + "</li>"); //Append to our div!
this.appendIngredient();
},
//Load all ingredients asynchronous
getIngredients: function(){
this.collection.fetch({
success: _.bind(this.loadIngredientSuccessHandler, this),
error: _.bind(this.loadIngredientErrorHandler, this)
});
},
loadIngredientSuccessHandler: function(data, json){
for (var i= 0; i < json.length; i++){
data = {
ingrName: json[i]['name'], //Haal naam uit JSON op
ingrSort: json[i]['sort'], // Haal soort uit JSON op
ingrDescription: json[i]['description'], //Haal Beschrijving uit JSON op
ingrPrice: json[i]['price'],
ingrBakeTime: json[i]['bake-time'],
ingrVegi: json[i]['vegetable']
};
//Create a template and append it to $el.
var template = _.template(this.ingredientTemplate.html(), data, this);
this.$el.append(template);
}
},
appendIngredient: function(data){
this.description = data.ingrDescription;
$("#steps").append(this.description);
},
//Error handler if something went wrong
loadIngredientErrorHandler: function(collection, response, options){
console.log("If something went wrong!")
}});
謝謝!
對不起,對不起!我對Backbone相當陌生,想知道如果使用JSON文件更好,那麼只需將它們添加到我的模型中。 –
檢查編輯,看看這是否爲你澄清的東西。 – Trace