Resting Model and collection on every click before fetch - backbone.js
Hi i have been working on app where onclick of the image you can add pin on the image anywhere and store its name and details. All work fine like i can add details and save it and it get saved into the database. But if you go back to another link and come back on the same. It shows the older stuff instead of the saved one in database.
I tried resetting and removing the model and collection but it doesnt work. Also tried destroying the model but it shows up errr as
Object function (){ return parent.apply(this, arguments); } has no method 'reset'
Below is my code :
/*MLP Backbone Starts Here*/
var MLPImage = Backbone.Model.extend({
});
var MLPImages = Backbone.Collection.extend({
model : MLPImage,
url: jQuery('#baseurl').val()+'index.php/api/example/scmlps/',
initialize : function(){
/*if(MLPImage.destroy()){
console.log("destroyed")
}else{
console.log("not destroyed")
}*/
this.deleteTask();
console.log(this)
this.on("reset", this.loadMLPImagesView,this);
this.on("pushpindata", this.pushpindetailsview,this);
this.on("error", this.errorMLPImageMessage,this);
this.on("mlperror", this.errorMLPpushpin,this);
console.log(this)
},
deleteTask: function() {
that = this;
this.model.reset();
this.model.destroy({
success: function() {
console.log(that.parent.collection);
}
});
return false;
},
loadMLPImagesView : function(){
// console.log(this);
//console.log(this.CollView.$el);
if(!this.CollView){
this.CollView = new MLPImagesView({collection:this})
}
this.CollView.render();
},
errorMLPImageMessage : function(){
jQuery('#imageBlocksDiv').html('<span id="noMsg"><h4>No images to display.</h4></span>');
},
pushpindetailsview : function(){
if(!this.pushpinview){
this.pushpinview = new pushpindetailsViews({collection:this})
}
this.pushpinview.render();
},
errorMLPImageMessage : function(){
jQuery('#clickable').append('<span id="noMsg"><h4>No images to display.</h4></span>');
}
});
var MLPImagesView = Backbone.View.extend({
el : jQuery('#imageBlocksDiv'),
events : {
'click .middle-box-title' : 'setsavevisisble',
'click .box-comment' : 'setsavevisisble',
'click .imagepopup' : 'mlppopupimage',
'click #closeme' : 'closepopup',
'click #closesave' : 'closepindetails',
'click #details' : 'savepushpindetails',
'click #closeupdate' : 'closeupdatepushpin',
'click .ui-draggable-mlp': 'passpushpindobjid',
'dragenter img.ui-draggable-mlp' : 'alertMe',
},
alertMe: function (e) {
jQuery(e.currentTarget).draggable({ containment: "parent" });
jQuery(e.currentTarget).mouseup(function(){
var x = jQuery(this).css("left");
var x_myarr = x.split("px");
var x_val = x_myarr[0];
var y = jQuery(this).css("top");
var y_myarr = y.split("px");
var y_val = y_myarr[0];
//console.log(jQuery(this).attr('data-objectid'))
objid = jQuery(this).attr('data-objectid');
var inputData = {
'total_img_des' : jQuery('#clickable').html(),
'x_val' : x_val,
'y_val' : y_val,
'id' : objid
};
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
//console.log(response)
}
});
});
},
setsavevisisble : function(ev){
jQuery(jQuery(ev.currentTarget).parents().eq(1).find('#saveGallery')).css('display','block');
},
closepindetails : function(){
jQuery('.close').show();
jQuery('#title').val('');
jQuery('#description').val('');
jQuery('.pinDetails').hide();
jQuery('.popupmlp').find('.ui-draggable-mlp').last().remove();
},
closeupdatepushpin : function(){
jQuery('.close').show();
jQuery('.updatepin').hide();
},
passpushpindobjid : function(ev){
var that = this;
var leftval = jQuery(ev.currentTarget).css('left');
var topval = jQuery(ev.currentTarget).css('top');
jQuery(ev.currentTarget).parents().eq(0).append("<img id='pushpin_loader' style='position:absolute;left:"+leftval+";top:"+topval+";' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />");
jQuery('.updatepin').remove();
jQuery('#updatetitle').val('');
jQuery('#updatedescription').html('');
var img_id = jQuery(ev.currentTarget).attr('data-objectid'); //console.log(img_id)
that.retrivepushpindetails(img_id);
},
savepushpindetails : function(ev){
var popup_id = jQuery('.pinDetails').attr('data-popupid');
jQuery('#popup'+popup_id).find('#btn').html("<img style='float:right;margin: 15px 5px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />");
var x = jQuery('.popupmlp img[data-uniqueid="'+popup_id+'"]').css("left");
var x_myarr = x.split("px");
var x_val = x_myarr[0];
var y = jQuery('.popupmlp img[data-uniqueid="'+popup_id+'"]').css("top");
var y_myarr = y.split("px");
var y_val = y_myarr[0];
var inputData = {
'description': jQuery('#description').val(),
'title': jQuery('#title').val(),
'imageid' : jQuery('#hideobjid').val(),
'projectId' : jQuery('#ugallerymlp').val(),
'total_img_des' : jQuery('#clickable').html(),
'pushpin_number' : popup_id,
'x_val' : x_val,
'y_val' : y_val,
'canvas_height' : jQuery('#clickable').height(),
'canvas_width' : jQuery('#clickable').width()
};
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
jQuery('.popupmlp img[data-uniqueid="'+popup_id+'"]').attr('data-objectid',response.objectId);
/*var inputData = {
'total_img_des' : jQuery('#clickable').html(),
'id' : response.objectId
};
jQuery.ajax({
'type':'POST',
'url': 'http://www.dwellar.com/portal/index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
}
});*/
alert("Saved");
jQuery('#popup'+popup_id).find('#btn').html('<input type="button" name="details" value="Save Detail" id="details">');
jQuery('#title').val('');
jQuery('#description').val('');
jQuery('.pinDetails').hide();
jQuery('.close').show();
}
});
},
mlppopupimage : function(ev){
var that = this;
jQuery("#clickable").html('');
jQuery('#mlpimagepopup').remove();
jQuery('#imageBlocksDiv').append('<div id="mlpimagepopup"></div>');
jQuery('#mlpimagepopup').append('<div class="pinDetails"><div id="closesave"><img src="http://www.dwellar.com/portal/assets/images/closenew.png"></div><table style="float:left; width:100%;"><tbody><tr><td style="height: 40px;"><span>Title :</span></td><td><span><input type="text" name="title" id="title" class="title" style="width: 162;"></span></td></tr><tr><td style="padding-top: 6%;height: 40px;"><span style="vertical-align: top;">Description :</span></td><td><span><textarea name="description" id="description" class="description" style="width: 98%;"></textarea></span></td></tr><tr><td id="btn" colspan="3"><input type="button" name="details" value="Save Detail" id="details"></td></tr></tbody></table></div>');
var hidval = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('id');
var imgurl = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src'); //console.log(imgurl)
jQuery.ajax({
'type':'GET',
'url': jQuery('#baseurl').val()+'index.php/api/authentication/randomdata/scpushpin_details/imageid/'+hidval,
success : function(response){
//console.log(response.length)
for(var i = 0; i<response.length; i++){
jQuery('#clickable').append('<img src="http://www.elementalcrafts.com/dwellarportal/images/location.png" style="position:absolute;height:35px;width:22px;left:'+response[i].x_val+';top:'+response[i].y_val+'" data-objectid="'+response[i].objectId+'" class="ui-draggable-mlp" title="'+response[i].title+'"data-uniqueid ="'+response[i].pushpin_number+'">');
}
}
});
jQuery('#mask').show();
jQuery('#mlpimagepopup').show();
jQuery('#mlpimagepopup').append('<input type="hidden" value="'+hidval+'" id="hideobjid"><div class="close" id="closeme" style="margin: -14px -8px 0px 0px;font-size: 30px;"><img src="http://www.dwellar.com/portal/assets/images/closenew.png"></div><div style="margin:7px;" class="popupmlp" id="clickable"><img src="'+imgurl+'"></div>');
//jQuery('#clickable').append('<div></div>');
jQuery('.popupmlp').bind('click', function (ev) {
jQuery('.close').hide();
jQuery('.ui-draggable-mlp').each(function(){
var pinval = jQuery(this).attr('data-objectid');
if(typeof pinval == 'undefined'){
var pi = jQuery(this).attr('data-uniqueid');
jQuery('img[data-uniqueid="'+pi+'"]').remove();
}
});
var divId = document.getElementById("clickable");
var divChild = jQuery('.popupmlp img').length;
var currentElemId= divChild+1;
var jQuerydiv = jQuery(ev.target);
var offset = jQuerydiv.offset();
var x = ev.clientX - offset.left ; //console.log(x)
var y = ev.clientY - offset.top ;
var xfloor = Math.floor(x);
var yfloor = Math.floor(y);
var scrollval = jQuery('.scrollval').last().attr('value'); //console.log(scrollval)
if(scrollval){}
else{
var scrollval = "0";
}
var nsv = Number(+yfloor + +scrollval); //console.log(nsv);
var pinImgElement= jQuery('<img class="ui-draggable-mlp">'); //console.log(pinImgElement);
pinImgElement.appendTo(jQuery(this));
pinImgElement.css({left:xfloor,top:nsv-25,'position':'absolute','width':'22px'}).attr('src','http://www.elementalcrafts.com/dwellarportal/images/location.png');
//pinImgElement.booklet( {keyboard: true} );
pinImgElement.draggable({ containment: "parent"});
pinImgElement.attr('data-uniqueid',currentElemId);
jQuery('.pinDetails').show();
jQuery('.pinDetails').attr('id','popup'+currentElemId);
jQuery('.pinDetails').attr('data-popupid',currentElemId);
jQuery('.updatepin').remove();
jQuery('#title').focus();
pinImgElement.on('click',function(){
var img_id = jQuery(this).attr('data-objectid');
that.retrivepushpindetails(img_id);
});
});
},
retrivepushpindetails : function(img_id){
jQuery('.pinDetails').hide();
jQuery('.ui-draggable-mlp').each(function(){
var pinval = jQuery(this).attr('data-objectid'); //console.log(pinval)
if(typeof pinval === 'undefined'){
var pi = jQuery(this).attr('data-uniqueid');
jQuery('img[data-uniqueid="'+pi+'"]').remove();
}
});
var that = this;
this.collection.fetch({data: jQuery.param({'objectid':img_id}), success:function(resp){
// console.log(resp)
that.collection.trigger("pushpindata");
},
error : function(){
//that.collection.trigger("mlperror");
}
});
},
closepopup : function(){
jQuery('#mask').fadeOut(100);
jQuery('#mlpimagepopup').fadeOut(500);
new pushpindetailsViews().cleanup();
},
initialize : function(){
var that = this;
jQuery('#ugallerymlp').change(function(){
that.filterByProjectsMLPImage(jQuery('#ugallerymlp').val());
});
},
render : function(){
this.iterateMsg();
},
iterateMsg : function(){
var that = this;
jQuery('#imageBlocksDiv').html('');
_.each(this.collection.models, function (msg) {
that.renderMsg(msg)
//console.log(msg)
});
pinterest();
},
renderMsg : function(msg){
var mV = new MLPImageView({
model : msg
});
this.$el.append(mV.render().el);
},
filterByProjectsMLPImage : function(projectId){//alert('thius');
var that = this;
var projectId = jQuery('#ugallerymlp').val();
//console.log(projectId,this.collection)
this.collection.fetch({data: jQuery.param({'projectId': projectId}), success:function(resp){
//console.log(resp)
that.collection.trigger("reset");
},
error : function(){
that.collection.trigger("error");
}
});
},
cleanup: function() {
//this.undelegateEvents();
$(this.el).find('#mlpimagepopup').empty();
//jQuery(this.el).find('#mlpimagepopup').empty();
}
});
var pushpindetailsViews = Backbone.View.extend({
el : jQuery('#mlppushpindetails'),
render : function(){
var that = this;
_.each(this.collection.models, function (pusmsg) {
that.pushpinMsg(pusmsg);
//console.log(pusmsg)
});
},
pushpinMsg : function(pusmsg){
var pmV = new mlppushpindetails({
model : pusmsg
});
this.$el.append(pmV.render().el);
},
cleanup: function() {
this.undelegateEvents();
$(this.el).empty();
}
});
var mlppushpindetails = Backbone.View.extend({
template : jQuery('#pushpindetails').html(),
events : {
'click #updatepushpin': 'passpushpindtails',
'click #deletepushpin': 'passpushpindtails',
'click #closeupdate' : 'closeupdatepopup',
},
render : function(){
//jQuery('#pushpinmlpdetails').html('');
jQuery('#pushpin_loader').remove();
_.bindAll(this,'updatepushpindetails')
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
//console.log(this.el);
return this;
},
closeupdatepopup: function(){
jQuery('.close').show();
jQuery('.updatepin').parents().eq(0).remove();
jQuery('.updatetitle').val('');
jQuery('.updatedescription').html('');
},
passpushpindtails:function(ev){
var selectedButton = jQuery(ev.currentTarget).attr('id');
var title= jQuery('.updatetitle').val();
var description = jQuery('.updatedescription').val();
var objId = jQuery('#hideval').val();
//console.log(selectedButton,objId)
selectedButton == 'updatepushpin' ? this.updatepushpindetails(objId,title,description): this.deletepushpindetails(objId);
//jQuery(jQuery(ev.currentTarget).parents().eq(1).find('#saveGallery')).css('display','none');
//jQuery('#updatepin').html("<img style='float:right;margin:5px 15px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />")
return false;
},
updatepushpindetails : function(objId,title,description){
jQuery('#updatepushpin').parents().eq(0).html("<img style='float:right;margin: 15px 5px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />")
var inputData = {
'title': title,
'description': description,
'id' : objId
};
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
alert('updated');
jQuery('.close').show();
jQuery('#updatetitle').html('');
jQuery('#updatedescription').html('');
jQuery('.updatepin').parents().eq(0).remove();
jQuery('#updatepushpin').parents().eq(0).html('<input type="button" name="Update" id="updatepushpin" class="updatepushpin" value="Update">')
}
});
},
deletepushpindetails : function(objId){
var r=confirm("Want to delete!")
if (r==true)
{
jQuery('#deletepushpin').parents().eq(0).html("<img style='float:right;margin: 15px 5px;' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />")
if(typeof objId!='undefined'){
var inputData = {
'id' : objId
}
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpspushpin/',
'data' : inputData,
success : function(response){
alert("Delete Pushpin")
//console.log(jQuery('#clickable').html(),jQuery('#currentimageid').val())
/*var inputData = {
'total_img_des' : jQuery('#clickable').html(),
'id' : jQuery('#currentobjid').val()
};
jQuery.ajax({
'type':'POST',
'url': 'http://www.dwellar.com/portal/index.php/api/example/scmlpspushpins/',
'data' : inputData,
success : function(response){
console.log(response)
}
});*/
jQuery('.updatepin').parents().eq(0).remove();
jQuery('.updatetitle').html('');
jQuery('.updatedescription').html('');
jQuery('.popupmlp img[data-objectid="'+objId+'"]').last().remove()
jQuery('.close').show();
jQuery('#deletepushpin').parents().eq(0).html('<input type="button" name="Delete" id="deletepushpin" class="deletepushpin" value="Delete">')
}
});
}
}
}
});
var MLPImageView = Backbone.View.extend({
className : "block",
initialize: function(){
var that = this;
jQuery('.inner-middle').mouseover(function(ev) {
jQuery(this).find('.editbutton').show();
}).mouseout(function(ev) {
jQuery(this).find('.editbutton').hide();
});
jQuery('.closedialog').click(function(){
jQuery('#dialog').fadeOut(1000);
});
},
template : jQuery('#mlpimagesBlock').html(),
events : {
'click #saveGallery': 'passImageDetails',
'click #deleteGallery': 'passImageDetails',
'click #sethome' : 'setashome',
'click .editbutton' : 'enableediting',
'click .box-comment' : 'enableediting',
'click .middle-box-title' : 'enableediting',
'click #cancelgallery' : 'cancelgallery',
},
enableediting : function(ev){
new galleryimageuploader(jQuery(ev.currentTarget).parents().eq(1).find('img').attr('id'))
var selectedButton = jQuery(ev.currentTarget).attr('class'); //console.log(selectedButton)
jQuery(ev.currentTarget).append('<input type="hidden" id="oldtitleval" value="'+jQuery(ev.currentTarget).parents().eq(1).find('#middle-box-title').text()+'"><input type="hidden" id="olddescriptoinval" value="'+jQuery(ev.currentTarget).parents().eq(1).find('#box-comment').text()+'"><input type="hidden" id="oldimagesrc" value="'+jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src')+'">');
jQuery('.editbutton').hide();
jQuery('.editbutton').attr('class','ch-inner');
jQuery('.box-comment').prop("contentEditable", false);
jQuery('.middle-box-title').prop("contentEditable", false);
jQuery('.box-comment').attr('class','changebox');
jQuery('.middle-box-title').attr('class','changetitle');
jQuery('.imagepopup').attr('class','changeimgstyle');
if(selectedButton == "box-comment" || selectedButton == "galleryimgstyle"){
jQuery(ev.currentTarget).parents().eq(2).find('.editbutton').hide();
jQuery(ev.currentTarget).parents().eq(2).find('.metadata').css('visibility','visible');
jQuery(ev.currentTarget).parents().eq(2).find('.changebox').css('z-index','9999');
jQuery(ev.currentTarget).parents().eq(2).find('.changetitle').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(2).find('.changetitle').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(2).find('.changebox').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(2).find('.changebox').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(2).find('.changeimgstyle').css("opacity", "0.4");
jQuery(ev.currentTarget).parents().eq(2).find('.gallerybox').show();
}
else{
jQuery(ev.currentTarget).parents().eq(1).find('.metadata').css('visibility','visible');
jQuery(ev.currentTarget).parents().eq(1).find('.changebox').css('z-index','9999');
jQuery(ev.currentTarget).parents().eq(1).find('.changetitle').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(1).find('.changebox').css('border','1px solid red');
jQuery(ev.currentTarget).parents().eq(1).find('.changebox').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(1).find('.changetitle').prop("contentEditable", true);
jQuery(ev.currentTarget).parents().eq(1).find('.changeimgstyle').css("opacity", "0.3");
jQuery(ev.currentTarget).parents().eq(1).find('.gallerybox').show();
}
return false;
},
render : function(){
_.bindAll(this,'saveImageDetails')
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
},
passImageDetails:function(ev){
var selectedButton = jQuery(ev.currentTarget).attr('id');
var imgTitle= jQuery(ev.currentTarget).parents().eq(1).find('#middle-box-title').text(); //console.log(imgTitle)
var imgDescription = jQuery(ev.currentTarget).parents().eq(1).find('#box-comment').text();
var imageUrl = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src');
var spl = imageUrl.substring(imageUrl.lastIndexOf('/')).split('/'); //console.log(spl[1])
var objId = jQuery(ev.currentTarget).parents().eq(1).find('img').attr('id');
//console.log(selectedButton,objId,imgTitle,imgDescription)
selectedButton == 'saveGallery' ? this.saveImageDetails(objId,imgTitle,imgDescription,imageUrl,ev): this.deleteImage(objId,spl[1],ev);
jQuery(jQuery(ev.currentTarget).parents().eq(1).find('.metadata')).html("<img style='float:right' src='http://www.dwellar.com/portal/assets/icon/dots.gif' />").css('height','28px');
return false;
},
saveImageDetails : function(objId,imgTitle,imgDescription,imageUrl,sethomeid){
var inputData = {
'name': imgTitle,
'description': imgDescription,
'image_url' : imageUrl,
'projectId' : jQuery('#ugallerymlp').val()
};
inputData.id = (objId != null) ? objId:"";
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlps/',
'data' : inputData,
success : function(response){
if(typeof response.objectId!='undefined'){
jQuery('.block').find("img[src='"+inputData.image_url+"']").attr('id',response.objectId);
jQuery('#'+response.objectId).parents().eq(2).find('div[id="tmploader"]').hide();
jQuery('#'+response.objectId).parents().eq(2).find('div[id="displaysus"]').attr('id',response.objectId);
}
jQuery('#'+response.objectId).parents().eq(2).find('.metadata').css({'visibility':'hidden','height':'28px'});
if(sethomeid == "abc"){
//jQuery('#dialog').show();
jQuery('#'+response.objectId).parents().eq(2).find('div[id="'+response.objectId+'"]').show()
jQuery('#'+response.objectId).parents().eq(2).find('div[id="'+response.objectId+'"]').fadeOut(3000);
}
else{
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="cancelgallery" href="##" style="color:white;margin: 0px;padding: 3px;background: #b2da8e;margin: 0 14% 0 0;" class="gallerystyle">Cancel</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
}
if(objId){jQuery('.metadata').css({'visibility':'hidden','height':'28px'});}
jQuery('#'+objId+'abc').show();
jQuery('#'+objId+'abc').fadeOut(3000);
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css('opacity', '1');
jQuery('.gallerybox').hide();
}
});
},
deleteImage : function(objId,imageUrl,sethomeid){
//console.log(objId)
var r=confirm("Want to delete!")
if (r==true)
{
if(typeof objId!='undefined'){
var inputData = {
'id' : objId,
'imgurl' : imageUrl
}
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlp/',
'data' : inputData,
success : function(response){
if(objId){jQuery('.metadata').css({'visibility':'hidden','height':'28px'});}
jQuery('#'+objId).parents().eq(3).remove();
pinterest(undefined);
if(sethomeid == "abc"){
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
pinterest(undefined);
}
else{
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="cancelgallery" href="##" style="color:white;margin: 0px;padding: 3px;background: #b2da8e;margin: 0 14% 0 0;" class="gallerystyle">Cancel</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
}
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css("opacity", '1');
jQuery('.gallerybox').hide();
pinterest(undefined);
jQuery.ajax({
'type':'POST',
'url': jQuery('#baseurl').val()+'index.php/api/example/scmlpdetails/',
'data' : inputData,
success : function(resdata){ console.log(resdata)}
});
}
});
}
}
else{
jQuery('.metadata').css({'visibility':'hidden','height':'28px'});
jQuery('.metadata').html('<a id="saveGallery" href="#" style="color:white;margin: 0px;padding: 3px;" class="gallerystyle">Save</a><a id="cancelgallery" href="##" style="color:white;margin: 0px;padding: 3px;background: #b2da8e;margin: 0 14% 0 0;" class="gallerystyle">Cancel</a><a id="deleteGallery" href="#" style="color:white;margin: 0px;padding: 3px;float:left;background:#d94a38;" class="gallerystyle">Delete</a>');
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css("opacity", '1');
jQuery('.gallerybox').hide();
pinterest(undefined);
}
},
cancelgallery : function(ev){
jQuery(ev.currentTarget).parents().eq(1).find('#middle-box-title').text(jQuery('#oldtitleval').val());
jQuery(ev.currentTarget).parents().eq(1).find('#box-comment').text(jQuery('#olddescriptoinval').val());
jQuery(ev.currentTarget).parents().eq(1).find('img').attr('src',jQuery('#oldimagesrc').val());
jQuery('.metadata').css({'visibility':'hidden','height':'28px'});
jQuery('.changebox').css('border','none');
jQuery('.changetitle').css('border','none');
jQuery('.changebox').prop("contentEditable", false);
jQuery('.changetitle').prop("contentEditable", false);
jQuery('.ch-inner').attr('class','editbutton')
jQuery('.changebox').attr('class','box-comment');
jQuery('.changetitle').attr('class','middle-box-title');
jQuery('.changeimgstyle').attr('class','imagepopup');
jQuery('.imagepopup').css("opacity", '1');
jQuery('.gallerybox').hide();
pinterest(undefined);
}
});
/MLP Backbone Ends Here/
Can anyone help me with the destroying and clearing the collection and model. Any help is deeply appreciated.
Thanking you,
Santosh Upadhayay
My first reaction would be to confirm that you don't have 2 of the same view on the page. I suspect that your original view still exists when you navigate back to the page. So it's this view that's being shown before your updated view which makes you think it's not being updated. So confirm that the html you expect to see isn't showing up in the wrong place.
If, on the other hand, you never see the correct html (even after the first interaction), then I suspect it has to do with your rendering logic. The model may be correctly syncing with the server, but you're not listening to the correct events from the view; or perhaps you are listening to the model event, but your handler is NOT rendering the view again.
Related
Angular leaflet - Showing multiple marker issue
I am using the following code to add markers in leaflet: .controller('MapController', [ '$scope', '$cordovaGeolocation', '$stateParams', '$ionicModal', '$ionicPopup', '$http', function( $scope, $cordovaGeolocation, $stateParams, $ionicModal, $ionicPopup, $http ) { $scope.$on("$stateChangeSuccess", function() { $scope.map = { defaults: { tileLayer: 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', maxZoom: 18, zoomControlPosition: 'bottomleft' }, markers : {}, events: { map: { enable: ['context'], logic: 'emit' } } }; $scope.locate(); }); $scope.locate = function(){ $scope.map.center = { lat : location.lat, lng : location.lng, zoom : 12, }; var Location = function() { if ( !(this instanceof Location) ) return new Location(); this.lat = ""; this.lng = ""; this.name = ""; }; $ionicModal.fromTemplateUrl('templates/addLocation.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal; }); $scope.map.markers.push=({ lat:35.654, lng:73.244, message:'demo 1' }) $scope.map.markers.push=({ lat:38.654, lng:73.244, message:'demo 2' }) $scope.$on('leafletDirectiveMap.click', function(event, locationEvent){ $scope.newLocation = new Location(); $scope.newLocation.lat = locationEvent.leafletEvent.latlng.lat; $scope.newLocation.lng = locationEvent.leafletEvent.latlng.lng; $scope.modal.show(); }); $scope.saveLocation = function(lat, lang) { //LocationsService.savedLocations.push($scope.newLocation); //alert(lat + " - " + lang); var link = 'http://192.168.5.110/server/addLocation.php'; var json1 = {l1 : lat, l2 : lang , l3: sessionStorage.getItem('loggedin_phone')}; $http.post(link, { data: json1 }) .then(function (res){ $scope.response = res.data.result; if($scope.response.created=="1"){ $scope.title="Thank You"; $scope.template="Mobile Toilet Added!"; //no back option /* $ionicHistory.nextViewOptions({ disableAnimate: true, disableBack: true }); $state.go('login', {}, {location: "replace", reload: true}); */ }else if($scope.response.exists=="1"){ $scope.title="Duplication"; $scope.template="This Location is already added!"; }else{ $scope.title="Failed"; $scope.template="Contact Our Technical Team"; } var alertPopup = $ionicPopup.alert({ title: $scope.title, template: $scope.template }); }); $scope.modal.hide(); }; $cordovaGeolocation .getCurrentPosition() .then(function (position) { $scope.map.center.lat = position.coords.latitude; $scope.map.center.lng = position.coords.longitude; $scope.map.center.zoom = 18; $scope.map.markers.now = { lat:position.coords.latitude, lng:position.coords.longitude, focus: true, draggable: false, //message: '' }; }, function(err) { // error console.log("Location error!"); console.log(err); }); }; }]); But only the demo2 marker is displaying. Is there a way to show multiple markers on the leaflet map by using JSON data of latitudes and longitudes loaded from API?
<leaflet defaults="defaults" event-broadcast="events" lf-center="center" markers="markers" layers="layers" id="global-map" width="100%" height="240px"></leaflet> <leaflet defaults="defaults2" event-broadcast="events2" lf-center="center2" markers="markers2" layers="layers2" id="global-map2" width="100%" height="240px"></leaflet>
backbone Cannot read property 'push' of undefined
i'm working with Backbone and when I generate the view I have the error Cannot read property 'push' of undefined". The line of the error is "self.subViewsReservas.push(new ReservaView({" in the push. ReservaCollectionView = Backbone.View.extend({ initialize: function () { if (Session.get('authenticated') && Session.get('authenticated') !== false) { this.paginacionVista = new PaginacionReservasView({ collection: this.collection, el: '.paginacionReservas', reservasPagina: 5, }); this.buscadorVista = new BuscadorView({ el: 'div.buscador-reservas', //Pasamos la colección oficinas ya que hará las veces del conjunto de oficinas retornadas por el servidor collection: new OficinasCollection(oficinas), }); } else { } }, render: function () { var self = this; this.template = _.template($('#divReservaTpl').html(), {}); self.$('.contenedor-reservas').empty(); self.collection.each(function (reserva, index) { self.$('.contenedor-reservas').append(self.template({'data': reserva.toJSON()})); }); this.collection.each(function (reserva, index) { this.subViewsReservas = []; self.subViewsReservas.push(new ReservaView({ el: '#' + reserva.get('Idreserva'), model: reserva })); }); this.collection.each(function (reserva, index) { //Limite de la paginacion 5 limite arbitrario if (index < 5) { //Lo Marcamos como visible y actualiazamos la paginación self.collection.get(reserva.get('Idreserva')).set({'Visibilidad': true}); } }); this.paginacionVista.render(); return this; }, }); AppView = Backbone.View.extend({ initialize : function(){ var self = this; self.usu = new UsuarioModel(); self.usu.fetch({ success: function (model){ Session.fetch({ success : function (){ Session.set('nombre',model.get('Nombre')); Session.set('apellidos',model.get('Apellidos')); Session.set('puntos_club',model.get('Puntosclub')); self.render(); } }); self.sideBar = new SideBarView({ el : '.sidebar', model: model }); self.sideBar.markOption('mis-reservas'); AppView = Backbone.View.extend({ initialize : function(){ var self = this; self.usu = new UsuarioModel(); self.usu.fetch({ success: function (model){ Session.fetch({ success : function (){ Session.set('nombre',model.get('Nombre')); Session.set('apellidos',model.get('Apellidos')); Session.set('puntos_club',model.get('Puntosclub')); self.render(); } }); self.sideBar = new SideBarView({ el : '.sidebar', model: model }); self.sideBar.markOption('mis-reservas'); }, error : function (){ document.location = '/mygoldcar/login'; } }); this.listenTo(Session, 'change', self.update); }, render : function(){ var self = this; var reservas = new ReservasCollection(); reservas.fetch({ success: function (collection){ if ( typeof collection.models[0].get('error') == 'undefined' || !collection.models[0].get('error')) { var listRes = new ReservaCollectionView({ el : '.reservas-list', collection: collection }); listRes.render(); var popoverModel = new Popover(); popoverModel.setData(collection.models[0].get('kilometraje_ilimitado'), collection.models[0].get('duracion')); self.popover = new PopoverView({ el: 'body', model: popoverModel }); self.popover.establecerPopover(); } else document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1'; }, error: function () { document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1'; } }); }, update: function() { var self = this; self.sideBar.update(Session.get('nombre'),Session.get('apellidos'),Session.get('puntos_club')); self.$el.find('.nombre-usuario').text(Session.get('nombre')); }, updatePoints: function() { var self = this; self.usu.fetch({ success: function (model){ Session.set('puntos_club',model.get('Puntosclub')); } }); } }); }, error : function (){ document.location = '/mygoldcar/login'; } }); this.listenTo(Session, 'change', self.update); }, render : function(){ var self = this; var reservas = new ReservasCollection(); reservas.fetch({ success: function (collection){ if ( typeof collection.models[0].get('error') == 'undefined' || !collection.models[0].get('error')) { var listRes = new ReservaCollectionView({ el : '.reservas-list', collection: collection }); listRes.render(); var popoverModel = new Popover(); popoverModel.setData(collection.models[0].get('kilometraje_ilimitado'), collection.models[0].get('duracion')); self.popover = new PopoverView({ el: 'body', model: popoverModel }); self.popover.establecerPopover(); } else document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1'; }, error: function () { document.location = '/mygoldcar' + self.urlLang(lang) + '/mi-cuenta/#msg/1'; } }); }, update: function() { var self = this; self.sideBar.update(Session.get('nombre'),Session.get('apellidos'),Session.get('puntos_club')); self.$el.find('.nombre-usuario').text(Session.get('nombre')); }, updatePoints: function() { var self = this; self.usu.fetch({ success: function (model){ Session.set('puntos_club',model.get('Puntosclub')); } }); } });
Inside collection.each, this points to the collection. So the property subViewsReservas is added to it, not the view instance. When you try to access it like self.subViewsReservas.push, self points to the view instance, which doesn't have subViewsReservas property, hence the error. Initializing an array inside each like you're doing isn't doing much since it'll be reset with each invocation of the callback. You should be initializing it in the initialize method, which is the right place to initialize things, where this will correctly point to the view instance as shown below initialize: function () { this.subViewsReservas = []; } For some reason if you want the collection to reset everytime, you can change the context to view by passing it as second argument to each like: this.collection.each(function (reserva, index) { this.subViewsReservas = []; self.subViewsReservas.push(new ReservaView({ el: '#' + reserva.get('Idreserva'), model: reserva })); }, self); // <--- makes view the context of callback, // both 'self' and 'this' will refer to view
angularjs directive is not rendered in browser
I am using this timepicker-popup directive from github: https://github.com/mytechtip/timepickerpop I am using it in my html: <timepicker-pop input-time="activeStep.timeTest" class="input-group" show-meridian='showMeridian'> </timepicker-pop> I do not understand, why the timepicker is not even initialized nor rendered. I am new to the directive stuff but when the directive is named: 'timepickerPop' how can it be that the demo here: https://github.com/mytechtip/timepickerpop/blob/master/demo/timepickerpop-demo.html uses in the html this format ???? What do I wrong? I get no errors in my browser console! /** * Anularjs Module for pop up timepicker */ angular.module('timepickerPop', [ 'ui.bootstrap' ]) .factory('timepickerState', function() { var pickers = []; return { addPicker: function(picker) { pickers.push(picker); }, closeAll: function() { for (var i=0; i<pickers.length; i++) { pickers[i].close(); } } }; }) .directive("timeFormat", function($filter) { return { restrict : 'A', require : 'ngModel', scope : { showMeridian : '=', }, link : function(scope, element, attrs, ngModel) { var parseTime = function(viewValue) { if (!viewValue) { ngModel.$setValidity('time', true); return null; } else if (angular.isDate(viewValue) && !isNaN(viewValue)) { ngModel.$setValidity('time', true); return viewValue; } else if (angular.isString(viewValue)) { var timeRegex = /^(0?[0-9]|1[0-2]):[0-5][0-9] ?[a|p]m$/i; if (!scope.showMeridian) { timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/; } if (!timeRegex.test(viewValue)) { ngModel.$setValidity('time', false); return undefined; } else { ngModel.$setValidity('time', true); var date = new Date(); var sp = viewValue.split(":"); var apm = sp[1].match(/[a|p]m/i); if (apm) { sp[1] = sp[1].replace(/[a|p]m/i, ''); if (apm[0].toLowerCase() == 'pm') { sp[0] = sp[0] + 12; } } date.setHours(sp[0], sp[1]); return date; }; } else { ngModel.$setValidity('time', false); return undefined; }; }; ngModel.$parsers.push(parseTime); var showTime = function(data) { parseTime(data); var timeFormat = (!scope.showMeridian) ? "HH:mm" : "hh:mm a"; return $filter('date')(data, timeFormat); }; ngModel.$formatters.push(showTime); scope.$watch('showMeridian', function(value) { var myTime = ngModel.$modelValue; if (myTime) { element.val(showTime(myTime)); } }); } }; }) .directive('timepickerPop', function($document, timepickerState) { return { restrict : 'E', transclude : false, scope : { inputTime : "=", showMeridian : "=", disabled : "=" }, controller : function($scope, $element) { $scope.isOpen = false; $scope.disabledInt = angular.isUndefined($scope.disabled)? false : $scope.disabled; $scope.toggle = function() { if ($scope.isOpen) { $scope.close(); } else { $scope.open(); } }; }, link : function(scope, element, attrs) { var picker = { open : function () { timepickerState.closeAll(); scope.isOpen = true; }, close: function () { scope.isOpen = false; } } timepickerState.addPicker(picker); scope.open = picker.open; scope.close = picker.close; scope.$watch("disabled", function(value) { scope.disabledInt = angular.isUndefined(scope.disabled)? false : scope.disabled; }); scope.$watch("inputTime", function(value) { if (!scope.inputTime) { element.addClass('has-error'); } else { element.removeClass('has-error'); } }); element.bind('click', function(event) { event.preventDefault(); event.stopPropagation(); }); $document.bind('click', function(event) { scope.$apply(function() { scope.isOpen = false; }); }); }, template : "<input type='text' class='form-control' ng-model='inputTime' ng-disabled='disabledInt' time-format show-meridian='showMeridian' ng-focus='open()' />" + " <div class='input-group-btn' ng-class='{open:isOpen}'> " + " <button type='button' ng-disabled='disabledInt' class='btn btn-default ' ng-class=\"{'btn-primary':isOpen}\" data-toggle='dropdown' ng-click='toggle()'> " + " <i class='glyphicon glyphicon-time'></i></button> " + " <div class='dropdown-menu pull-right'> " + " <timepicker ng-model='inputTime' show-meridian='showMeridian'></timepicker> " + " </div> " + " </div>" }; });
Backbone Views listening to collection events is firing multiple times
I'm facing a very weird problem using ListenTo on subviews. Basically I've a main view that contains multiple subviews. Those subviews are initialized when their parent view is also initialized. Some of those subviews are listening to the same global collection. One of those views is a form that allow me to insert new entries into the collection The second one is a list of all those entries contained into the collection. So, basically it looks like this $('button').on('click'.... app.views.MyMainView = new MyMainView() //launch new modal window //with html body = app.views.MyMainView.el var MyMainView = Backbone.view.extend({ initialize: function(){ // new Form_View() // new List_View() } }); var Form_View = Backbone.view.extend({ //get input value // create new entrie into the collection }); var List_View = Backbone.view.extend({ initialize: function(){ // listenTo(this.collection, 'add', this.addOne) // new List_View() this.addAll(); }, addAll: function(){...}, addOne: function(model){ .... } }); The problem is the following: When the user launch the modal for the first time and we add a new entry to the collection the listenTo add on the List_View fires as expected. If I close the modal and the user clicks on 'button' to launch the modal window once again if I add a new entrie the view will fire 2 times the function that is listening to the collection add event. If i close the modal again and re-open it the function will fire 3 times and so on. This is weird because I'm creating a new instance of the view and their subviews everytime the user clicks on the 'button'. That's why it doesn't make sense to me. Any help? EDIT I also checked my collection by listening to the 'add' event inside of it. var MyCollection = Backbone.View.extend({ initialize: function(){ this.listenTo( this, 'add', doSomething ); }, doSomething: function( model ){ //do something fires as it should be firing the event: 1 time per each item inserted } }) EDIT 2 var MyMainView = Backbone.View.extend({ ..... close_modal: function(e){ if(e){ e.preventDefault(); } var viewsLen = this.views.length, _that = this; _.each(this.views, function(view, key){ view.remove(); if(key + 1 == viewsLen ) _that.dialog.close(); }) } ... }) EDIT 3: ALL CODE //initialize modal $('button').on('click', function(){ app.views.storePayment_View = new StorePayment_View(); }) var TMPL_StorePayment = '<div class="store-payment">' + '<div class="store-payment-header">' + '<div class="client"></div>' + '<div class="status"></div>' + '</div>' + '<div class="payment-form"></div>' + '<div class="payment-list"></div>' + '<div class="x-form-actions">' + '</div>' + '</div>'; var StorePayment_View = Backbone.View.extend({ views: {}, wrappers: {}, collections: {}, events: { "click .back": "close_modal", "click .finish-payment": "finish_payment" }, initialize: function(){ var _that = this; this.dialog = new BootstrapDialog({ title: appLang["h67"], message: this.$el, closable: true, onhide: function(dialogRef){ _that.remove(); } }); this.dialog.realize(); this.dialog.getModalFooter().hide(); this.dialog.open(); this.$el.html('').append( TMPL_StorePayment ); this.wrappers.$client = this.$el.find('.client'); this.wrappers.$status = this.$el.find('.status'); this.wrappers.$payment_form = this.$el.find('.payment-form'); this.wrappers.$payment_list = this.$el.find('.payment-list'); this.wrappers.$form_actions = this.$el.find('.x-form-actions'); this.render() }, render: function(){ this.views.StorePaymentForm_View = new StorePaymentForm_View(); this.wrappers.$payment_form.html('').append( this.views.StorePaymentForm_View.el ); this.views.StorePaymentList_View = new StorePaymentList_View(); this.wrappers.$payment_list.html('').append( this.views.StorePaymentList_View.el ); }, close_modal: function(e){ if(e){ e.preventDefault(); } var viewsLen = this.views.length, _that = this; _.each(this.views, function(view, key){ view.remove(); if(key + 1 == viewsLen ){ _that.dialog.close(); } }) } }) var StorePaymentForm_View = Backbone.View.extend({ error_tmpl: _.template('<div class="alert alert-warning"><%= message %></div>') , template: _.template('<div> <div class="input-field"> <input type="text" class="montant form-control" value="<%= restant %>"> </div> <div class="input-select"> <select name="payment-type"><% _.each(paymentTypeList, function(paymentType){ %> <option value="<%= paymentType.typeMode %>"><%= paymentType.libelle %></option> <% }) %></select> </div> <div class="actions">Add newRemove All </div></div><div class="error_placeholder"></div>'), events:{ "click .add-new": "add_new", "click .remove-all": "remove_all" }, initialize: function(){ this.collection = app.collections.StorePaymentList; this.listenTo( this.collection, 'add', this.render ) this.listenTo( this.collection, 'destroy', this.render ) this.listenTo( this.collection, 'change', this.render ) this.listenTo( this.collection, 'reset', this.render ) this.render() }, render: function(){ console.log("RENDER FIRED ON STOREPAYMENTFORM") var restant = this.collection.getRestant(); if ( restant <= 0){ restant = 0; } this.$el.html('').append( this.template( { "restant" : restant, "paymentTypeList": app.collections.PaymentTypeList.toJSON() } ) ) var _that = this; setTimeout(function(){ _that.$el.find('select').selectBoxIt({ native: true, autoWidth: false }) _that.$el.find('input').focus(); }, 50 ) }, add_new: function(e){ console.log("add_new"); if(e){ e.preventDefault(); } var _that = this, input_val = this.$el.find('input').val(), select_val = this.$el.find('select :selected').val(), libelle = this.$el.find('select :selected').text(), wasNaN = false; input_val = parseInt(input_val); if (isNaN(input_val)){ wasNaN = true; input_val = 0; } if (wasNaN){ _that.$el.find('.error_placeholder').html( _that.error_tmpl( { "message": appLang["h69"] } ) ); } else { if ( input_val <= 0 ){ _that.$el.find('.error_placeholder').html( _that.error_tmpl( { "message": appLang["h70"] } ) ); } else { this.collection.add( new StorePaymentModel( { "libelle": libelle , "paymentId": select_val, "montant": input_val } ) ) } } }, remove_all: function(e){ if(e){ e.preventDefault(); } var _that = this; //dialog are you sure? var dialog = new BootstrapDialog({ title: "Do you want to continue", message: "Do you really want to empty your current list of payments?", buttons: [{ label: appLang["a187"], //cancel action: function(dialog) { dialog.close(); } }, { label: appLang["a1621"], //ok cssClass: 'btn-primary', action: function(dialog) { _that.collection.reset([]); dialog.close(); } }] }) dialog.realize(); dialog.open(); } }) var StorePaymentListItem_View = Backbone.View.extend({ events:{ "click .remove": "remove_item", "click .save": "save" }, template: _.template( '<%= libelle %> <%= montant %> <i class="fa fa-trash-o"></i>' ), tagName: 'li', className: 'list-group-item', initialize: function(){ this.render() //console.log("StorePaymentListItem_View initialized") this.listenTo( this.model, 'hide', this.remove ) }, render: function(){ this.$el.html('').append( this.template( this.model.toJSON() ) ) }, edit: function(){ this.render_edit(); }, save: function(e){ if (e){ e.preventDefault(); e.stopPropagation(); } this.render(); }, remove_item: function(e){ if (e){ e.preventDefault(); e.stopPropagation(); } this.model.destroy(); } }) var StorePaymentList_View = Backbone.View.extend({ $wrapper: $('<ul />', {'class': 'list-group' }), initialize: function(){ this.$el.html(''); this.collection = app.collections.StorePaymentList; this.listenTo( this.collection , 'add', this.addOne ); this.listenTo( this.collection , 'change', this.render ); this.listenTo( this.collection , 'reset', this.render ); this.render() }, render: function(){ var totalItems = this.collection.length; this.$wrapper.html('') if (totalItems == 0){ this.appendToRoot(); } else { this.addAll() } }, addAll:function(){ var _that = this, totalItems = this.collection.length; this.collection.forEach(function(model, key){ _that.addOne(model) if (totalItems == key + 1) _that.appendToRoot(); }) }, addOne:function( model ){ var storePaymentListItem_View = new StorePaymentListItem_View({ model: model }); this.$wrapper.append( storePaymentListItem_View.el ); }, appendToRoot:function(){ this.$el.html('').append( this.$wrapper ); } })
My guess is closing the modal doesn't call view.remove, and so we end up with a zombie view that is removed from the DOM but still lives in memory listening to events. Another guess is you never remove the List_View instance, so they are the zombies. In other words, this is likely to be related to insufficient garbage collection. This is a guess - it's impossible to tell without seeing the relevant parts of the code.
BackboneJS - Cannot call method 'on' of undefined
I have this simple BackboneJS app and it keeps returning this error on adding new model to collection: Cannot call method 'on' of undefined. Can someone help me. I can't see the problem in here.I have my templates defined in index.html, and I am using Slim framework and NotORM. (function(){ window.App = { Models:{}, Collections: {}, Views : {} } window.template = function(id) { return _.template( jQuery('#' + id).html()); } App.Models.Party = Backbone.Model.extend({ }); App.Collections.Partys = Backbone.Collection.extend({ model: App.Models.Party, url: "http://localhost/BackboneJS/vjezba6/server/index.php/task" }); App.Views.Party = Backbone.View.extend({ tagName :"div", className: "box shadow aktivan", template: template("boxovi"), initialize: function() { this.model.on('change', this.render, this); }, events:{ "click .izbrisi" : "izbrisi" }, render: function() { var template = this.template( this.model.toJSON() ); this.$el.html(template); return this; }, izbrisi: function() { this.model.destroy(); }, ukloni: function() { this.remove(); } }); App.Views.Partys = Backbone.View.extend({ tagName:"div", id: "nosac-boxova", initialize: function() { }, render: function() { this.collection.each(this.addOne, this); return this; }, addOne: function(party) { var partyView = new App.Views.Party({ model: party }); this.$el.append(partyView.render().el); } }); App.Views.Dodaj = Backbone.View.extend({ tagName: "div", template : template("dodajTemp"), events: { 'submit' : 'submit' }, submit : function(e) { e.preventDefault(); console.log(e); var nazivPolje = $(e.currentTarget).find(".naziv").val(); var tekstPolje = $(e.currentTarget).find(".lokal").val(); var noviParty = new App.Views.Party({naziv:nazivPolje, tekst: tekstPolje}); this.collection.create(noviParty); }, initialize: function() { }, render: function() { var template = this.template(); this.$el.html(template); return this; } }); /* var kolekcijaPartya = new App.Collections.Partys([ { naziv:"Ovo je prvi naziv", tekst: "Ovo je prvi tekst" }, { naziv:"Ovo je drugi naziv", tekst: "Ovo je drugi tekst" } ]);*/ var kolekcijaPartya = new App.Collections.Partys; kolekcijaPartya.fetch({ success: function() { var partysView = new App.Views.Partys({collection:kolekcijaPartya}); $("#content").prepend(partysView.render().el); $("div.box").slideAj(); var dodajView = new App.Views.Dodaj({collection: kolekcijaPartya}); $("div#sidebar-right").html(dodajView.render().el); } }); })();
var noviParty = new App.Views.Party({naziv:nazivPolje, tekst: tekstPolje}); this.collection.create(noviParty); so you are trying to add a View to your collection?