(编辑更多信息)
我正在 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!")
}});
谢谢!!
最佳答案
不确定我的问题是否正确。
您基本上需要在获取时为每种成分渲染一个新实例,并使用以下方式调用 View 中的描述:
this.model.get("description");
由于模型绑定(bind)到 View ,因此您不需要访问 DOM 来获取成分。
编辑:
我认为您要寻找的是首先获取集合:这将返回一个集合,其中每个成分都由模型(带有 id、名称、描述)表示。然后循环遍历集合并为每个模型实例化一个新 View ,之后您可以通过调用 this.model.get("description"); 来访问 View 中的模型。
注意:查看 Backbone 木偶;这使得渲染集合变得非常容易。
关于jquery - Backbone.js - 从 JSON 文件获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31204882/