2015-07-03 95 views
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!") 
}}); 

謝謝!

回答

0

不知道我是否正確的問題。
你基本上需要取出時,呈現一個新的實例每種成分,並通過調用視圖的描述:

this.model.get("description"); 

由於模型綁定到視圖,則無需訪問DOM來獲取配料。

編輯:
我想你要找的是你首先獲取集合:這將返回一個集合,每種成分由一個模型(與id,名稱,描述)代表。然後循環訪問集合併爲每個模型實例化一個新視圖,之後可以通過調用this.model.get("description");訪問視圖中的模型。

注意:檢查Backbone Marionette;這使得渲染集合非常容易。

+0

對不起,對不起!我對Backbone相當陌生,想知道如果使用JSON文件更好,那麼只需將它們添加到我的模型中。 –

+0

檢查編輯,看看這是否爲你澄清的東西。 – Trace