Nested CompositeViews with different sources instantiate multiple parent views instead of child - backbone.js

I have three views in my application. One ItemView (item) which is a child of CompositeView (category) which is a child of CompositeView (parentCategory).
I also waterfall instantiate my views based on API hits from data (in this case I'm using local data to give the impression of live data).
Here is my application in js form:
var App = new Backbone.Marionette.Application();
App.addRegions({
mainRegion: "#main"
});
var todoArray = [];
// A single row
var TodoRow = Backbone.Marionette.ItemView.extend({
template: "#todo-template",
tagName: "li",
events: {
'click span': 'clickSpan'
},
clickSpan: function() {
console.log(this);
}
});
// The grid view
var CategoryView = Backbone.Marionette.CompositeView.extend({
tagName: "li",
template: "#category-template",
itemView: TodoRow,
itemViewOptions: function(model, index) {
return {
parent: model.get('parent')
}
},
appendHtml: function(collectionView, itemView){
if(collectionView.id === itemView.model.get('parent')) {
itemView.render();
collectionView.$("ul.items").append(itemView.el);
}
}
});
var TabView = Backbone.Marionette.CompositeView.extend({
tagName: "li",
template: "#tab-template",
itemView: CategoryView,
itemViewOptions: function(model, index) {
return {
parent: model.get('parent')
}
},
appendHtml: function(collectionView, itemView){
if(collectionView.id === itemView.model.get('parent')) {
itemView.render();
collectionView.$("ul.categories").append(itemView.el);
}
}
});
var Tab = Backbone.Model.extend({}),
Category = Backbone.Model.extend({}),
Todo = Backbone.Model.extend({});
var TabCollection = Backbone.Collection.extend({
model: Tab,
url: 'tab.json'
});
var CategoryCollection = Backbone.Collection.extend({
model: Category,
url: 'category.json'
});
var TodoCollection = Backbone.Collection.extend({
model: Todo,
url: 'todo.json'
});
var todoList,
todoFetch,
categoryList,
categoryFetch,
tabList,
tabFetch;
App.addInitializer(function() {
console.log(data);
todoList = new TodoCollection(data.items);
todoFetch = todoList.fetch();
categoryList = new CategoryCollection(data.categories);
tabList = new TabCollection(data.tabs);
var todoCallback = function() {
//categoryFetch = categoryList.fetch();
//categoryFetch.done(categoryCallback);
categoryCallback();
},
categoryCallback = function() {
//tabFetch = tabList.fetch();
//tabFetch.done(tabCallback);
tabCallback();
},
tabCallback = function() {
tabList.each(function(tab, index) {
var sampleCatList = _.filter(categoryList.models, function(category) {
if(tab.get('id') === category.get('parent')) return true;
return false;
});
tabView = new TabView({
collection: new TabCollection(sampleCatList),
id: tab.get('id'),
model: tab
});
tabView.render();
$('#main ul').append(tabView.el);
});
};
//todoFetch.done(todoCallback);
todoCallback();
});
App.start();
I have a working JSFiddle here: http://jsfiddle.net/Pq5s7/
There should be three two level li's Roger & Wilko
Then there should be two categories, and one item underneath each category.

Related

How to filter backbone collection to show tags

I'm creating a bookmarking tool that lets you create a list of stored bookmarks from an in-page form. The list will include an identifier tag (eg - Amazon www.amazone.com tag: shopping). From this created list, I want to also have a list showing the various tags that have been named.
This should probably use the filter method, but I cannot seem to get it to filter a correct list; I keep getting each tag listed for each URL created so there are multiple examples of the same tag.
Here is the code that correctly works in creating my form, the resulting URL list, and the module exports. This is from my Views js file:
var $ = require('jquery');
var Backbone = require('backbone');
var listTemplate = require('../../templates/addresslist.hbs');
var formTemplate = require('../../templates/addressform.hbs');
var detailTemplate = require('../../templates/addressdetail.hbs');
var AddressFormView = Backbone.View.extend({
tagName: 'form',
template: formTemplate,
events: {
'submit': 'addAddress'
},
render: function(){
var renderedHtml = this.template();
this.$el.html(renderedHtml);
return this;
},
addAddress: function(event){
event.preventDefault();
this.collection.create({
title: $('#title').val(),
url: $('#url').val(),
tag: $('#tag').val(),
});
$('#title').val('');
$('#url').val('');
$('#tag').val('');
},
});
var AddressListView = Backbone.View.extend({
tagName: 'ul',
initialize: function(){
this.listenTo(this.collection, 'add', this.renderItem);
},
render: function(){
return this;
},
renderItem: function(address){
console.log('address', address);
var addressItem = new AddressItemView({model: address});
this.$el.append(addressItem.render().el);
}
});
var AddressItemView = Backbone.View.extend({
tagName: 'li',
template: listTemplate,
render: function(){
var context = this.model.toJSON();
this.$el.html(this.template(context));
return this;
}
});
var AddressDetailView = Backbone.View.extend({
template: detailTemplate,
render: function(){
this.$el.html('').append(this.template);
return this;
}
});
module.exports = {
'AddressFormView': AddressFormView,
'AddressListView': AddressListView,
'AddressItemView': AddressItemView,
'AddressDetailView': AddressDetailView,
}
My router js file looks like this:
var $ = require('jquery');
var Backbone = require('backbone');
var views = require('./views/addressview');
var models = require('./models/address');
var Router = Backbone.Router.extend({
routes: {
'': 'index',
'detail/:id/': 'detail'
},
initialize: function(){
this.collection = new models.AddressCollection();
},
index: function(){
var addressForm = new views.AddressFormView({collection: this.collection});
$('.app').html(addressForm.render().el);
var addressListing = new views.AddressListView({collection: this.collection});
$('.app').append(addressListing.render().el);
this.collection.fetch();
},
detail: function(addressId){
this.collection.fetch().done(function(){
var address = this.collection.get(addressId);
var addressDetail = new views.AddressDetailView({model: address});
$('.app').html(addressDetail.render().el);
}.bind(this));
},
});
var router = new Router();
module.exports = router;
Create new event in view for multiple tag selection
tagSelected :function(event){
var tags = [<tag1>,<tag2>] //getting from multiple tag selection
var models = _.filter(this.collection.models,function(model){
return tags.indexOf(model.get('tag')) >= 0;
})
this.collection.reset(models);
this.render();
})

Marionette, backbone js betting game

This is a betting game, made in backbone. I have a bounty of 100 to help me refactor it into a marionette based application.
I am unsure where to start - in terms of reconfiguring the models, how to swap the views out to make them regions.
I believe the steps would be to start with creating a new marionette application and router.
var app = Marionette.Application.extend({
initialize: function(options) {
console.log('My container:', options.container);
}
});
var app = new app({container: '#app'});
//router
var MyRouter = Marionette.AppRouter.extend({
appRoutes: {
"some/route": "someMethod"
},
routes : {
"some/otherRoute" : "someOtherMethod"
},
someOtherMethod : function(){
// do something here.
}
});
Then create a few regions and layouts to manage old backbone views.
//regions
MyApp.addRegions({
bankValue: "#bankvalue",
bitValue: "#bitvalue"
});
Then convert the old backbone views to Marionette's ItemViews and CompositeViews.
//compositeview
var CompositeView = Marionette.CompositeView.extend({
template: "#personalbank"
});
new CompositeView({
model: userModel,
collection: someCollection
});
Here is the latest js fiddle.
//UserBankModel
var UserBankModel = Backbone.Model.extend({
defaults: {
chips: 200
},
initialize: function() {
console.log("UserBankModel initialize");
this.on("change:chips", function(model) {
var chips = model.get("chips"); // 23232
console.log("Changed my chips to " + chips);
});
}
});
//UserBankView
var UserBankView = Backbone.View.extend({
initialize: function() {
console.log("UserBankView initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
//BitcoinModel
var BitcoinModel = Backbone.Model.extend({
defaults: {
currentValue: 0,
lockedValue: 0
},
initialize: function() {
console.log("BitcoinModel initialize");
this.on("change:currentValue", function(model) {
var currentValue = model.get("currentValue"); // 494
console.log("Changed my currentValue to " + currentValue);
});
},
getBitcoinValue: function(callback) {
/*
Backbone.ajax({
dataType: 'json',
url: "https://api.bitcoinaverage.com/ticker/USD",
crossDomain: true,
success: function(data) {
callback(data);
}
});
*/
json= {
bid: 320,
ask: 444
};
var mediumValue = (json.bid + json.ask) / 2;
callback(mediumValue);
}
});
//BitcoinView
var BitcoinView = Backbone.View.extend({
initialize: function() {
console.log("BitcoinView initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
var App = Backbone.Model.extend({
initialize: function() {
var that = this;
this.userBankModel = new UserBankModel();
this.userBankView = new UserBankView({
el: $("#bankvalue")
});
this.bitcoinModel = new BitcoinModel();
this.bitcoinView = new BitcoinView({
el: $("#bitvalue")
});
//setInterval(function() {
//get val of bitcoin every second
that.bitcoinModel.getBitcoinValue(function(mediumVal) {
//set bit coin model
that.bitcoinModel.set({
currentValue: mediumVal
});
//render the bit coin value
that.bitcoinView.render(that.bitcoinModel.get("currentValue"));
});
//}, 1000);
//render users chips
this.userBankView.render(this.userBankModel.get("chips"));
},
currentBitcoinValue: 0,
startBet: function(state) {
console.log("start timer");
this.state = state;
//get locked value of bitcoin for the game
var stashValue = this.bitcoinModel.get("currentValue");
//set bit coin model with locked value
this.bitcoinModel.set({
lockedValue: stashValue
});
var initialTimer = 5;
var Timer = {
i: initialTimer,
onTimer: function() {
var that = this;
document.getElementById('timer').innerHTML = Timer.i;
Timer.i--;
if (Timer.i < 0) {
app.gameResult();
Timer.i = initialTimer; //reset
} else {
setTimeout(Timer.onTimer, 1000);
}
}
};
Timer.onTimer();
},
gameResult: function() {
console.log("whats the result then");
console.log("this.state", this.state);
var lockedValue = this.bitcoinModel.get("lockedValue");
var currentValue = this.bitcoinModel.get("currentValue");
console.log("lockedValue>>", lockedValue);
console.log("currentValue>>", currentValue);
var result = "loss";//lose by default
//locked value was higher
if (
this.lockedValue > this.currentValue && this.state["bet"] == "high" ||
this.lockedValue < this.currentValue && this.state["bet"] == "low"
) {
result = "win";//win if conditions are met
}
//get current value of user chips
var newVal = this.userBankModel.get("chips");
if (result == "win") {
console.log("WIN -- you get chips");
newVal += this.state["wager"];
} else {
console.log("LOSS -- you loose chips");
newVal -= this.state["wager"];
}
//won or lost chips -- set new chip value
this.userBankModel.set({
chips: newVal
});
//render new user chips
this.userBankView.render(this.userBankModel.get("chips"));
}
});
var app = new App();
var FormView = Backbone.View.extend({
el: '#wager-form',
events: {
"submit": "doMethod"
},
doMethod: function(e) {
e.preventDefault();
var obj = [];
this.$el.find('input[name]').each(function() {
obj[this.name] = this.value;
});
//start bet
app.startBet(obj);
}
});
var form = new FormView();
I would like to know more about the best practice in using Marionette with backbone. Why use Marionette, what is the advantage?
Is it a simple case of refactoring the following example. Or does a Marionette based method work more like a collection?
var App = Backbone.Model.extend({
initialize: function() {
//standard app
}
});
But would this be the way to refactor the App model to use Marionette?
var App = Marionette.Application.extend({
initialize: function(options) {
console.log('My container:', options.container);
//invoke other models
this.otherModel1 = new OtherModel1();
this.otherView1= new OtherView1({
el: $("#selector1")
});
}
});
//add the selectors in one place?
MyApp.addRegions({
someRegion: "#some-div",
anotherRegion: "#another-div"
});
// Although applications will not do anything
// with a `container` option out-of-the-box, you
// could build an Application Class that does use
// such an option.
var app = new App({container: '#app'});
This is the structure of my application. How would I refactor it properly to use marionette
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>backbone js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20150503/json2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.marionette/2.4.4/backbone.marionette.js"></script>
</head>
<body>
Content of the document......
<div id="app"></div>
<div id="select1"></div>
<div id="select2"></div>
<script>
//myModel1
var MyModel1 = Backbone.Model.extend({
initialize: function() {
console.log("myModel1 initialize");
}
});
//myView1
var MyView1 = Backbone.View.extend({
initialize: function() {
console.log("myView1 initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
//myModel2
var MyModel2 = Backbone.Model.extend({
initialize: function() {
console.log("myModel2 initialize");
}
});
//myView2
var MyView2 = Backbone.View.extend({
initialize: function() {
console.log("myView2 initialize");
this.render();
},
render: function(value) {
this.$el.html(value);
}
});
//the core that invokes and bridges the other models.
var App = Backbone.Model.extend({
initialize: function() {
var that = this;
this.myModel1 = new MyModel1();
this.myView1 = new MyView1({
el: $("#select1")
});
this.myModel2 = new MyModel2();
this.myView2 = new MyView2({
el: $("#select2")
});
}
});
var app = new App();
/*ok marionette stuff*/
var MyApp = Marionette.Application.extend({
initialize: function(options) {
console.log(options.container);
}
});
var myApp = new MyApp({container: '#app'});
</script>
</body>
</html>
Ok so would the code kind of look like this? Where I pump the models into the options variable?
MyApp.addInitializer(function(options){
// do useful stuff here
var otherView1= new OtherView1({
model: options.otherModel1
});
MyApp.mainRegion.show(otherView1);
});
MyApp.addInitializer(function(options){
new MyAppRouter();
Backbone.history.start();
});
this is my current application - but I am unsure how to structure it with marionette moving forward?
Latest fiddle of the entire core application.
Ok so, I have my application with standard backbone like this..
with a core Model that invokes and bridges the other models. Something like this.
Old backbone way
var App = Backbone.Model.extend({
initialize: function() {
this.myModel1 = new MyModel1();
this.myView1 = new MyView1({
el: $("#select"),
model: this.myModel1
});
this.myModel2 = new MyModel2();
this.myView2 = new MyView2({
el: $("#select"),
model: this.myModel2
});
}
});
so is Marionette supposed to work like this?
App.addInitializer(function(options) {
App.myModel1 = new MyModel1();
App.myView1 = new MyView1({
el: $("#select1"),
model: App.myModel1
});
App.myModel2 = new MyModel2();
App.myView2 = new MyView2({
el: $("#select2"),
model: App.myModel2
});
});
and what about regions.. Do I stop using el: selectors for the view and rely on regions? And if so, how?
var View1Region = Backbone.Marionette.Region.extend({
el: "#select1", // Must be defined for this syntax
// Whatever other custom stuff you want
});
var View2Region = Backbone.Marionette.Region.extend({
el: "#select2", // Must be defined for this syntax
// Whatever other custom stuff you want
});
// Use these new Region types on App.
App.addRegions({
view1Region: View1Region,
view2Region: View2Region
});
// This is equivalent to:
App.view1Region = new View1Region();
App.view2Region = new View2Region();
I've made a new jsfiddle to start structuring the marionette version.
but am I invoking it correctly, using the new composite view correctly.
//UserBankModel
var UserBankModel = Backbone.Model.extend({
defaults: {
chips: 200
},
initialize: function() {
console.log("UserBankModel initialize");
this.on("change:chips", function(model) {
var chips = model.get("chips"); // 23232
console.log("Changed my chips to " + chips);
});
}
});
var CompositeView = Marionette.CompositeView.extend({
template: "#personalbank"
});
var userBankView = new CompositeView({
model: UserBankModel
});
var MyApp = Marionette.Application.extend({
initialize: function(options) {
console.log('My container:', options.container);
this.userBankModel = new UserBankModel();
}
});
var app = new MyApp({
container: '#app'
});
app.addRegions({
bankValue: "#bankvalue",
bitValue: "#bitvalue"
});
If we focus on the view for a second, how would I refactor this in the way I was intending to.
html
<div id="list"></div>
<script type="text/template" id="list-template">
<div class="pagination">
<ul></ul>
</div>
</script>
<script type="text/template" id="item-template">
<%= id %>
</script>
js
var Item = Backbone.Model.extend();
var Items = Backbone.Collection.extend({
model: Item
});
var Views = {};
Views.ListItem = Backbone.Marionette.ItemView.extend({
template: "#item-template",
tagName: 'li'
});
Views.List = Backbone.Marionette.CompositeView.extend({
template: "#list-template",
itemView: Views.ListItem,
itemViewContainer: "ul"
});
var Data = [
{id: 1},
{id: 2}
];
var items = new Items(Data);
var list = new Views.List({
collection: items
});
list.render();
$("#list").html(list.el);
http://jsfiddle.net/c72Vg/168/
A while ago the answer would have been "no", use Marionette's Application.addInitializer(function () {}) but when Marionette v3 is released that will be removed and in it's place you're expected to use events.

Backboe memory leak in subviews

I still strugling with memory leak in my app. I wannted to do it without huge changes in code.
var ItemsView = Backbone.View.extend({
id:'products', // If I change it to el: document.getElementById('products') and without passing views into items object, my views are properly rendered but with memory leak
events: { },
initialize: function() {
_.bindAll(this);
this.listenTo(this.collection, 'reset', this.reset);
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'change', this.changeItem);
this.listenTo(this.collection, 'destroy', this.delItem);
this.items = [];
},
reset: function(){ console.log("reset");
this.el.innerHTML = null;
this.render();
},
render: function(){
for(var i=0; i < this.collection.length; i++){
this.renderItem(this.collection.models[i]);
}
},
renderItem: function( model ){
var itemView = new ItemView({ model: model });
itemView.render();
this.items.push(itemView);
jBone(this.el).append(itemView.el);
},
addItem: function(){ console.log("addItem");
this.renderItem();
},
changeItem: function(){ console.log("changeItem"); },
delItem: function(){ console.log("delItem"); },
remove: function() {
_.invoke(this.items, 'remove');
this.items = [];
Backbone.View.prototype.remove.call(this);
}
});
return ItemsView;
This is my Itemsview it is executed when user hit orderview, there is created ItemView for every model in collection:
var ItemView = Backbone.View.extend({
tagName: "li",
className: "productcc",
initialize: function () {
_.bindAll(this, 'addItem', 'removeItem', 'updateItem');
this.listenTo(this.model, 'remove', this.removeItem);
this.listenTo(this.model, 'change', this.updateItem);
},
events: {},
render: function () {
var model = this.model.toJSON();
this.el.innerHTML += '<div class="tabody"><h4 class="tablename">'+model.title+'<h4>'+model.status+'</div>';
return this;
},
addItem: function(){
this.collection.create({"table_no":"demo"});
},
changeItem: function(e){
e.preventDefault();
this.model.save({ table_no: 'demo' });
},
updateItem: function(newstuff){
console.log("updateItem");
console.log(this.el);
},
delItem: function(){
this.model.destroy({ silent: true });
},
removeItem: function(model){
console.log("removeItem");
console.log(model);
var self = this;
self.el.remove();
}
});
return ItemView;
MY ROUTER:
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'home',
'home' : 'home',
'customer/:customer_id': 'showItems'
}
});
var initialize = function(options) {
window.app_router = new AppRouter;
window.socket = io.connect('www.example.com');
this.socketOrdersCollection = new SocketOrdersCollection();
this.ordersView = new OrdersView({ collection: this.socketOrdersCollection });
this.socketOrdersCollection.fetch({ reset: true });
app_router.on('route:home', function() { });
app_router.on('route:showItems', function(customer_id) {
if (this.itemsView) {
this.itemsView.remove();
}
this.socketItemsCollection = new SocketItemsCollection();
this.socketItemsCollection.fetch({ data: { id: customer_id}, reset: true });
this.itemsView = new ItemsView({
collection: this.socketItemsCollection,
model: { tableName: customer_id }
});
});
Backbone.history.start();
};
I have to remove also ItemsView after click to another order...
Thanks for any opinion.
Ok. Let me take a stab at what you're attempting here.
var ItemsView = Backbone.View.extend({
el: document.getElementById('products'),
events: { },
initialize: function() {
// everything you had before
this.items = [];
},
// etc.
renderItem: function( model ){
var itemView = new ItemView({ model: model });
itemView.render();
this.items.push(itemView);
jBone(this.el).append(itemView.el);
},
// etc.
// we're overloading the view's remove method, so we clean up our subviews
remove: function() {
_.invoke(this.items, 'remove');
this.items = [];
Backbone.View.prototype.remove.call(this);
}
});
return ItemsView;
And then in the router:
var initialize = function(options) {
// etc.
app_router.on('route:home', function() { });
app_router.on('route:showItems', function(customer_id) {
if (this.itemsView) {
this.itemsView.remove();
}
// everything else the same
});
Backbone.history.start();
};
So now, your ItemsView will clean up any child items it has, and when you change customers, you'll clean up any ItemsView you have open before generating a new one.
EDIT
I see what you're having a problem with now.
In your route handler, you're going to need to do something along these lines:
app_router.on('route:showItems', function(customer_id) {
// everything you already have
jBone(document.getElementById('container')).append(this.itemsView);
});

How to delete a dependent model from the same collection in backbone.js

I have a model which has both navid and subnavid .While destroying a model i need to check in the entire collection , for other models which have navid as same as subnavid of the model i'am trying to delete . Please help me out . Thanks in advance . Heregoes my sample code.
Model:
var Node = Backbone.Model.extend({
defaults: {
NavId: '',
SubNavId: ''.
ItemName:''
} }
Collection:
var NodeCollection = Backbone.Collection.extend({ model:Node }
And i have two view one for the Node(i am building tr) and other for
the collection(I need to build table) var NodeCollectionView =
Backbone.View.extend({
initialize: function (options) {
var self = this; self.collection = new NodeCollection({ NavigationId: options.NavigationId });
self.collection.fetch({
success: function () {
/*I am getting hte proper collection from my restful api and iam able to bind it properly
self.render();
}
});
},
render: function () {
var that = this;
_.each(this.collection.models, function (item) {
that.RenderEachNode(item);
}, this);
},
RenderEachNode: function (item) {
var TempJsonNode = item.toJSON();
var self = this;
var nodeView = new NodeView({
tagName: 'tr',
id: 'NavId_' + TempJsonNode.NavItemId,
model: item
});
} });
var ItemTemplate = ""; ItemTemplate += " <td>"; ItemTemplate += " <a><%= ItemName %></a>"; ItemTemplate +=" </td>"; ItemTemplate
+=" <td>"; ItemTemplate +=" <a href='#' original-title='Delete ' class='tip_north Delete'>X</a>"; ItemTemplate +=" </td> ";
var NavigationItemView = Backbone.View.extend({
template: ItemTemplate,
render: function () {
var self = this;
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
},
events: {
"click .Delete": "DeleteBtnClick"
},
DeleteBtnClick: function () {
var self = this;
self.model.destroy({
success: function (status, data) {
var RetData = JSON.parse(data);
if (RetData.Status == 'Success') {
$(self.el).remove()
}
},
error: function () {
alert('Error In Deleting The Record');
}
});
return false;
} });
I am able to build the table properly but while destroying a model , i am not figuring out a way to destroy the dependent models.My Api is restricted in such a way that i cannot get a nested json ( if so i would have done with backbone relation). so i need to figure out some way that the other models and views which has the NavId of the model am deleting.
Please help me out.
How about something like:
var NodeView = Backbone.View.extend({
initialize: function() {
//when the model gets destroyed, remove the view
this.listenTo(this.model, 'destroy', this.remove);
},
//..clip
DeleteBtnClick: function () {
var self = this;
var collection = self.model.collection;
var navId = self.model.get('NavId');
self.model.destroy({
success: function (status, data) {
var RetData = JSON.parse(data);
if (RetData.Status == 'Success') {
//if parent was part of a collection
if (collection) {
//find related models
var related = collection.filter(function (model) {
return model.get('SubNavId') === navId;
});
//call destroy for each related model.
var promises = _.invoke(related, 'destroy');
//optional: if you want to do something when all the children
//are destroyed:
$.when.apply($, promises).then(function () {
console.log('all destroyed');
});
}
}
},
error: function () {
console.log(arguments);
alert('Error In Deleting The Record');
}
});
return false;
}
});
Edit: JSFiddle here

backbone.js events not firing after re-render even with delegateEvents()

I have a View whit nested views inside that when rendered has a link on it with a click event attached. First time I click on al link, all works. But when re-render all views, links events are disappeared. I tried forcing delegateEvents() in render and remove views before re-render but nothing.
Here is my code:
var SlideView = Backbone.View.extend({
tagName: 'li',
events: {
'click .nested':'destroy'
},
template: _.template($('#slides-nested-template').html()),
render: function(e){
var _el = $(this.el);
_el.html(this.template(this.model.toJSON()));
this.delegateEvents(this.events);
return this;
},
destroy: function(e){
e.preventDefault();
Presentations.eliminate($(e.target).attr('rel'));
}
});
var SectionView = Backbone.View.extend({
tagName: 'li',
template: _.template($('#slides-template').html()),
events: {
'click .no-nested':'destroy'
},
initialize: function(options){
this.views = [];
_.bindAll(this, 'destroy');
},
render: function(){
var _el = $(this.el), self=this;
_el.html(this.template(this.model.toJSON()));
_ul = this.$('ul');
var data = Presentations.filter(function(slide){
return slide.get('padre') == self.model.get('id');
});
_.each(data, function(slide){
view = new SlideView({
model: slide
});
self.views.push(view);
_ul.append(view.render().el);
});
this.delegateEvents(this.events);
return this;
},
destroy: function(e){
e.preventDefault();
Presentations.eliminate($(e.target).attr('rel'));
},
removeViews: function(){
while (this.views.length){
var view = this.views.shift();
view.undelegateEvents();
view.remove();
view = null;
}
}
});
var SectionList = Backbone.View.extend({
tagName: 'ul',
className: 'sortable',
initialize: function(options){
Presentations.on('add', this.render, this);
Presentations.on('reset', this.render, this);
Presentations.on('remove', this.render, this);
this.views = [];
},
render: function(e){
//this.removeViews();
$('#slides .content').empty();
var data = Presentations.filter(function(slide){
return slide.get('padre') === false;
});
var view, self=this, _el=$(this.el);
_.each(data, function(slide){
view = new SectionView({
model: slide
});
_el.append(view.render().el);
self.views.push(view);
});
$('#slides .content').append(_el);
return this;
},
removeViews: function(){
while (this.views.length){
var view = this.views.shift();
view.undelegateEvents();
view.removeViews();
view.remove();
view = null;
}
}
});
var Presentation = Backbone.Model.extend({
});
var PresentationList = Backbone.Collection.extend({
model: Presentation,
url: BASE_URL+'api/slides/'+PRESENTATION,
eliminate: function(id){
this.each(function(slide){
if (slide.get('padre')==id){
slide.set('padre', false);
slide.save();
}
});
var ref = this.get(id);
ref.destroy();
this.remove(ref);
}
});
Presentations = new PresentationList();
SectionListView = new SectionList();
Presentations.fetch();

Resources