我正在做我的第一个骨干应用程序,并且我尝试附加事件时发生了一件奇怪的事情。对所有视图都支持的骨干视图事件
我得到这个代码至今:
//View for @girl, EDIT action
GirlEditView = Backbone.View.extend({
initialize: function(el, attr) {
this.variables = attr;
console.log(attr);
this.render();
},
render: function() {
var template = _.template($("#girl_edit").html(), this.variables);
$(this.el).html(template);
$("#edit_girl").modal('show');
}
});
//View for @girl
GirlView = Backbone.View.extend({
initialize: function(el, attr) {
this.variables = attr;
this.render();
},
render: function() {
var template = _.template($("#girl_template").html(), this.variables);
$(this.el).html($(this.el).html() + template);
},
events: {
"click p.modify": "modify"
},
modify: function() {
//calls to modify view
new GirlEditView({el : $("#edit_girl")}, this.variables);
}
});
//One girl from the list
Girl = Backbone.Model.extend({
initialize: function() {
this.view = new GirlView({el : $("#content")}, this.attributes);
}
});
//all the girls
Girls = Backbone.Collection.extend({
model: Girl,
});
//do magic!
$(document).ready(function() {
//Underscore template modification
_.templateSettings = {
escape : /\{\[([\s\S]+?)\]\}/g,
evaluate : /\{\[([\s\S]+?)\]\}/g,
interpolate : /\{\{([\s\S]+?)\}\}/g
}
//get initial data and fill the index
var list = [];
$.getJSON('girls.json', function(data) {
list = [];
$.each(data, function(key, val) {
list.push(new Girl(val));
});
var myGirls = new Girls(list);
console.log(myGirls.models);
});
});
正如你所看到的。
我正在使用一个集合来存储所有的女孩,并且数据来自Ruby中的REST api。
每个女孩创建一个新的模型实例,并在里面附加一个视图实例。
我不知道这是否是一个好的做法,但我想不出一个更好的方法来做到这一点。
每个视图都使用唯一的ID生成内容。女孩1女孩2继续。
现在,该模板有一个编辑按钮。 我最初的想法是攻击onclick事件并触发编辑视图来呈现。
这是按预期工作。
的proble迄今:
当事件触发,所有的集合(女孩)火编辑视图,而不是“拥有”渲染视图之一。
我的问题是我做错了什么?
非常感谢
好吧,我想我得到模型在骨干的观点,我做了改变,但现在什么都没有显示在页面http://pastebin.com/96vhsDPu – nax
@nax:你没有呈现你的'GirlsView “任何地方; 'this.collection.each'循环可能在'render'而不是'initialize'中更好:http://jsfiddle.net/ambiguous/3fHkh/ –