backbonejs remove anomaly concept
Posted
by
user1537158
on Stack Overflow
See other posts from Stack Overflow
or by user1537158
Published on 2012-11-24T14:19:05Z
Indexed on
2012/11/25
5:04 UTC
Read the original article
Hit count: 170
jQuery
|backbone.js
I was building a small app for adding and deleting li from ul using Backbonejs.One of the SO members cymen helped me code it, using that i tailored the code a little.currently if i add one element and delete , it works , but the second time i add an element (to ul) and go to delete it , i get
Uncaught TypeError: Cannot call method 'remove' of undefined
Pasting my code here ,
HTML :
<input type="text" id="name">
<button id="add">Add</button>
<ul id="mylist"></ul>
JS:
$(function(){
var myCollection = Backbone.Collection.extend();
var myView = Backbone.View.extend({
el:$('body'),
tagName:'li',
initialize : function(e){
this.collection.bind("add",this.render,this);
this.collection.bind("remove",this.render,this);
},
events:{
'click #add' : 'addfoo'
},
addfoo : function(){
var myname= $('#name').val();
$('#name').val('');
this.collection.add({name:myname});
},
render : function(){
$('#mylist').empty();
this.collection.each(function(model){
console.log("myView");
var remove = new myRemoveView({model:model});
remove.render();
});
}
});
var myRemoveView = Backbone.View.extend({
el:$('body'),
events:{
'click .button':'removeFoo'
},
removeFoo : function(){
console.log("here");
this.model.collection.remove(this.model);
},
render : function(){
console.log("second view");
$('#mylist').append('<li>'+this.model.get('name') + "<button class='button'>"+"delete"+"</button></li>");
return;
}
});
var view = new myView({collection: new myCollection()});
});
Two things i did not understand :
i) in the removeFoo function , we write
this.model.collection.remove(this.model)
shouldnt this have been this.collection.model.remove , something of that sort ?
ii) i add a li to ul , then i delete it , when i add another li (appending to ul works perfect) but this time when i go to delete it throws me the above error : Uncaught TypeError :cannot call method 'remove' of undefined
can you please help me figure out these 2 doubts in my code , btw SO member cymen's code works like a charm only my tailored code (above) is giving me errors.
SO member cymen's code : JS Fiddle for his code
Thank you
© Stack Overflow or respective owner