开发一个简单的应用程序来添加和删除ul中的名称。我有一个输入和一个按钮,当我点击按钮时,输入中的文字被附加到ul.My代码是:
<input type="text" placeholder="Enter friend's name" id="input" />
<button id="add-input">Add Friend</button>
<ul id="friends-list">
</ul>
骨干代码:
<script>
$(function() {
FriendList = Backbone.Collection.extend({
initialize: function(){
this.bind("add", function( model,options ){
var id = ( model.collection.indexOf(model) );
view.render(model,id);
});
this.bind("remove",function(model){
alert("here");
});
}
});
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click #add-input': 'getFriend',
'click .button': 'removeFriend'
},
initialize: function() {
this.friendslist = new FriendList;
_.bindAll(this, 'render');
},
getFriend: function() {
var friend_name = $('#input').val();
this.friendslist.add( {name: friend_name} );
},
removeFriend: function(){
var friend_index = $('.button').attr('id');
alert(friend_index);
this.friendslist.remove();
},
render: function( model,id ) {
$("#friends-list").append("<li>"+ model.get("name")+"<button class=button id="+id+">"+"delete"+"</button>"+"</li>");
$('#input').val('');
}
});
var view = new FriendView({el: 'body'});
});
</script>
我的问题,我被困住了:
i)添加功能运行得很好,当我点击删除按钮时,它会转到removeFriend功能,但不会转到收集和提醒(“这里”); ii)请帮我编写删除/删除li的代码,点击删除按钮
谢谢
答案 0 :(得分:2)
Backbone入门令人困惑。我开始假设它可以在默认情况下做得更多。相反,它是构建基础的构建块(参见主干木偶和类似项目)。我已经在考虑这些事情的情况下重构了你的代码:
FriendView
有太多的知识:它不应该知道将自己插入DOM的位置。remove
的集合上的FriendListView
事件。那么如何修复你的代码呢?这就是我所做的:http://jsfiddle.net/Gd2Rs/
$(function() {
FriendList = Backbone.Collection.extend();
FriendListView = Backbone.View.extend({
initialize: function(e, c) {
this.collection.bind('add', this.render, this);
this.collection.bind('remove', this.render, this);
},
events: {
'click #add-input': 'addFriend'
},
addFriend: function() {
var friend_name = $('#input').val();
$('#input').val('');
this.collection.add({name: friend_name});
},
render: function() {
var list = this.el.find('#friends-list');
list.empty();
this.collection.each(function(model) {
var friendView = new FriendView({model: model});
list.append(friendView.render().el);
});
}
});
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click .button': 'removeFriend'
},
removeFriend: function(){
this.model.collection.remove(this.model);
},
render: function() {
$(this.el).html(this.model.get('name') + "<button class='button'>"+"delete"+"</button>");
return this;
}
});
var view = new FriendListView({
el: $('#friends'),
collection: new FriendList()
});
});
请注意,我故意避免优化FriendListView.render
,因为我认为使用Backbone是错误的方法。您将需要构建自己的集合渲染,您应该重用或使用像主干木偶这样的东西。使用Backbone的锅炉板代码直接令人厌烦。