【发布时间】:2011-12-14 23:40:07
【问题描述】:
我正在通过创建一个表视图和一个单独的行视图并尝试将行添加到表中来试验 Backbone.js:
我有:
- 联系人模型
- 联系人集合
- 联系人视图(充当 主视图)
- ContactRow 视图
到目前为止,该项目运行良好 - 除了应该触发添加行的功能的按钮。
到目前为止,这是我的代码:
$(function($) {
window.Contact = Backbone.Model.extend({
defaults: {
first_name: "John",
last_name: "Smith",
address: "123 Main St"
}
});
window.Contacts = Backbone.Collection.extend({
model: Contact
});
window.ContactRow = Backbone.View.extend({
//el: $("#contacts-table table tbody"),
row_template: _.template($("#contact-row").html()),
initialize: function() {
_.bindAll(this, "render")
},
render: function() {
$("tbody").html("<tr><td>Look at me, I'm a row!</td></tr>");
return this;
}
});
window.ContactsView = Backbone.View.extend({
el: $("#contacts-container"),
events: {
"click button#add_contact": "addContact"
},
template: _.template($("#contacts-table").html()),
initialize: function() {
_.bindAll(this, "render", "addContact", "appendContact");
this.collection = new Contacts();
this.collection.bind("add", this.appendContact);
var contactRow = new ContactRow();
this.render();
this.appendContact(); // Just a test to see if the function is working
},
render: function() {
$("#button-container").append("<button id='add_contact'>Add Contact</button>");
$(this.el).html(this.template);
_(this.collection.models).each(function(contact) {
appendContact(contact);
}, this)
},
addContact: function() {
console.log("yup, it works!"); // well, not yet
var contact = new Contact();
this.collection.add(contact);
},
appendContact: function(contact) {
var contactRow = new ContactRow({
model: contact
});
$("body").append(contactRow.render().el);
}
});
var contactsView = new ContactsView();
}, jQuery);
如您所见,我有一个 addContact 函数,该函数与“添加联系人”按钮的单击事件相关联,该按钮在渲染过程中被附加到主页上的 div 元素.
我正在尝试将日志消息写入控制台,但按钮似乎没有触发该方法,我不知道为什么。
这是一天的结束,我的大脑被炸了,所以我很感激任何关于这个的指点。谢谢。
【问题讨论】:
标签: javascript jquery backbone.js