using localStorage in Backbone.js - backbone.js

I am putting together a backbone example in which models are created edited and deleted. I am able to save new models and edits to local storage, but am having a problem getting localstorage to properly display on refresh. It seems to be loading as a single object, and therefore gives me one model regardless of how many were added.
var Thing = Backbone.Model.extend({
defaults: {
title: 'blank'
}
});
var ThingView = Backbone.View.extend({
template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
events: {
"click #remove": "deleteItem",
"click #edit": "editItem",
"click #save": "saveItem",
},
deleteItem: function () {
console.log('deleted');
this.model.destroy();
this.remove();
},
editItem: function () {
console.log('editing');
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveItem: function () {
console.log('saved');
editTitle = $('input.name').val();
console.log(editTitle);
this.model.save({
title: editTitle
});
this.$el.html(this.template(this.model.toJSON()));
},
render: function () {
var attributes = this.model.toJSON();
this.$el.append(this.template(attributes));
return this;
}
});
var ThingsList = Backbone.Collection.extend({
model: Thing,
localStorage: new Store("store-name"),
});
var storeVar = localStorage.getItem("store-name");
console.log(storeVar);
var thingsList = new ThingsList;
thingsList.reset(storeVar);
var ThingsListView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'insertItem',
},
initialize: function () {
this.render();
this.collection.on("add", this.renderThing, this);
},
insertItem: function (e) {
newTitle = $('input').val();
newThing = new Thing({
title: newTitle
});
this.collection.add(newThing);
newThing.save();
console.log(this.collection.length);
},
render: function () {
_.each(this.collection.models, function (items) {
this.renderThing(items);
}, this);
},
renderThing: function (items) {
var thingView = new ThingView({
model: items
});
this.$el.append(thingView.render().el);
}
});
var thingsListView = new ThingsListView({
collection: thingsList
});

You need to add the items to your collection, and then to read it in you need to call fetch. You also have a couple of extra trailing commas in your objects.
Here's a slightly modified version of your code which seems to work.
var Thing = Backbone.Model.extend({
defaults:{
title:'blank'
}
});
var ThingView = Backbone.View.extend({
//el: $('body'),
template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
events: {
"click #remove": "deleteItem",
"click #edit": "editItem",
"click #save": "saveItem",
},
deleteItem: function(){
console.log('deleted');
this.model.destroy();
//remove view from page
this.remove();
},
editItem: function(){
console.log('editing');
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveItem: function(){
console.log('saved');
editTitle = $('input.name').val();
console.log(editTitle);
this.model.save({title: editTitle});
this.$el.html(this.template(this.model.toJSON()));
},
render: function(){
var attributes = this.model.toJSON();
this.$el.append(this.template(attributes));
return this;
}
});
var storeVar = localStorage.getItem("store-name");
var ThingsList = Backbone.Collection.extend({
model: Thing,
localStorage: new Store("store-name")
});
var things = [
{ title: "Macbook Air", price: 799 },
{ title: "Macbook Pro", price: 999 },
{ title: "The new iPad", price: 399 },
{ title: "Magic Mouse", price: 50 },
{ title: "Cinema Display", price: 799 }
];
console.log(things);
var thingsList = new ThingsList;
var ThingsListView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'insertItem'
},
initialize: function () {
this.render();
this.collection.on("add", this.renderThing, this);
},
insertItem: function(e){
newTitle = $('input').val();
newThing = new Thing({ title: newTitle });
this.collection.add(newThing);
newThing.save();
//this.model.saveItem;
console.log(this.collection.length);
},
render: function(){
_.each(this.collection.models, function (items) {
this.renderThing(items);
}, this);
},
renderThing: function(items) {
//console.log('added something');
var thingView = new ThingView({ model: items });
items.save();
this.$el.append(thingView.render().el);
}
});
var thingsListView = new ThingsListView( {collection: thingsList} );
thingsList.fetch();
console.log(thingsList.toJSON());
thingsList.reset(things);
Edit: I see you are trying to read in the value stored in local storage under "store-name", the way backbone-localStorage works is that it uses the name of the store (in your case "Store-name") to store the ids of the rest of the models and then saves each model under a combination of the store name and the id, so say you had three models, you would end up with 4 entries in local storage,
localStorage["store-name"] //id1, id2, id3"
localStorage["store-name-id1"] //model with id1
localStorage["store-name-id2"] // model with id2
localStorage["store-name-id3"] // model with id3
EDIT 2
Here's a link to a jsfiddle of your code, to start I'm leaving the line thingsList.fetch(); commented out, uncomment that line and comment out thingsList.add(things); and run it a second time and it should pull the models from local Storage (I left an alert in there).

var Thing = Backbone.Model.extend({
defaults: {
title: 'blank'
}
});
var ThingView = Backbone.View.extend({
template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
events: {
"click #remove": "deleteItem",
"click #edit": "editItem",
"click #save": "saveItem",
},
deleteItem: function () {
console.log('deleted');
this.model.destroy();
this.remove();
},
editItem: function () {
console.log('editing');
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveItem: function () {
console.log('saved');
editTitle = $('input.name').val();
console.log(editTitle);
this.model.save({
title: editTitle
});
this.$el.html(this.template(this.model.toJSON()));
},
render: function () {
var attributes = this.model.toJSON();
this.$el.append(this.template(attributes));
return this;
}
});
var ThingsList = Backbone.Collection.extend({
model: Thing,
localStorage: new Store("store-name"),
});
var storeVar = localStorage["store-name-7ee7d1e3-bbb7-b3e4-1fe8-124f76c2b64d"];
console.log(storeVar);
var thingsList = new ThingsList;
//thingsList.reset(storeVar);
var ThingsListView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'insertItem',
},
initialize: function () {
thingsList.fetch();
thingsList.toJSON();
this.render();
this.collection.on("add", this.renderThing, this);
},
insertItem: function (e) {
newTitle = $('input').val();
newThing = new Thing({
title: newTitle
});
this.collection.add(newThing);
newThing.save();
console.log(this.collection.length);
},
render: function () {
_.each(this.collection.models, function (items) {
this.renderThing(items);
}, this);
},
renderThing: function (items) {
var thingView = new ThingView({
model: items
});
this.$el.append(thingView.render().el);
}
});
var thingsListView = new ThingsListView({
collection: thingsList
});

Related

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);
});

Pass model in a view backbone

Hi I've this function in my router:
home: function() {
var attore= new Attore();
var page = new ListPostView({
model: this.attore
});
this.changePage(page);
},
and the model Attore is:
var Attore = Backbone.Model.extend({
defaults: {
"nome": "caesar salad",
"cognome": "ravioli"
},
});
return Attore;
});
but happens an error that tell me model is undefined in the view:
var ListPostView = Backbone.View.extend({
tagName: "ul",
id: "list",
template: Handlebars.compile(template),
initialize: function () {
console.log(attore);
this.model.bind("reset", this.render, this);
},
render: function (eventName) {
$(this.el).empty();
_.each(this.model.models, function (ad) {
$(this.el).append(new SinglePostView({
model: ad
}).render().el);
}, this);
return this;
}
});
return ListPostView;
});

backbone.js how to set el to specific div id

My understanding of the Backbone View is that each html element that needs to show model data can be a View by itself.
I wish to create view linked to a specific div to show model data.
My problem is that the code doesn't work if I use anything else than 'body' for el.
Following code does not work:
http://jsfiddle.net/GhaPF/9/
$(document).ready(function() {
var ToDo = Backbone.Model.extend({
defaults: { "date": "today",
"task": ""
},
initialize: function() {}
});
var ToDoList = Backbone.Collection.extend({
model: ToDo
});
var ToDoListView = Backbone.View.extend({
el: "#view1",
initialize: function(myTodoList) {
this.todolist = myTodoList;
this.todolist.bind('add', this.render, this);
},
render: function() {
text = this.todolist.toJSON();
string = JSON.stringify(text);
$(this.el).append(string);
return this;
},
events: {
"keypress #new-todo": "createOnEnter"
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!$("#new-todo").val()) return;
this.todolist.add({"task": $("#new-todo").val()});
$("#new-todo").val('');
}
});
$("#new-todo").focus();
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);
});
​
But if I use 'body' for el, it works as I want.
How can I set the el to a specific div ?
solution
http://jsfiddle.net/r3F8q/
you can also use this.setElement('#body1') in render
<div id="view-container">
<input id="new-todo" placeholder="text">
<div id="view1"></div>
<div id="view2"></div>
</div>
​
$(document).ready(function() {
var ToDo = Backbone.Model.extend({
defaults: { "date": "today",
"task": ""
},
initialize: function() {}
});
var ToDoList = Backbone.Collection.extend({
model: ToDo
});
var ToDoListView = Backbone.View.extend({
el: "#view-container",
initialize: function(myTodoList) {
this.todolist = myTodoList;
this.todolist.bind('add', this.render, this);
},
render: function() {
text = this.todolist.toJSON();
string = JSON.stringify(text);
this.$el.find('#view1').append(string);
return this;
},
events: {
"keypress #new-todo": "createOnEnter"
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!$("#new-todo").val()) return;
this.todolist.add({"task": $("#new-todo").val()});
$("#new-todo").val('');
}
});
$("#new-todo").focus();
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);
});
​
When you use "#view1"
"keypress #new-todo": "createOnEnter"
is not binded, because #new-todo is not within "#view1". Check API.

parsing + backbonejs

how to parse the response value..
i want to get the json value from the json value....but get problem in parsing....
var ListView = Backbone.View.extend({
el: '#app-container',
initialize: function() {
_.bindAll(this,"render");
console.log('ListView init.');
this.counter = 0;
this.collection = new FieldCollection();
this.collection;
this.render(this.collection);
},
events: {
'click #add': 'addItem'
},
render: function(val) {
console.log(val);
console.log('Render called.');
},
});
my json is as follow...
[
{
"name": "qqqqqqqqqqqqqqqqqqq",
"img": "qqqqqqqqqqqqqqqqqqqq"
},
{
"name": "eeeeeeeeeeeeeeeeeee",
"img": "eeeeeeeeeeeeeeeeeee"
},
{
"name": "ggggggggggggggggggg",
"img": "gggggggggggggggggggg"
}
]
my question is that how to parse the response value...
how to access the json value in the view...
var FieldCollection = Backbone.Collection.extend({
defaults: {
model: Field
},
model: Field,
url: 'http://localhost:8080/backbonejs/myjsoncollection.json',
initialize: function() {
console.log('FieldCollection init.');
},
parse: function(response) {
console.log(response);
return response;
}
});
this is the whole code...
$(function(){
var Field = Backbone.Model.extend({
defaults: {
name: "shaleen",
img: "not found",
},
initialize: function() {
// console.log(this.attributes.name);
}
});
var FieldCollection = Backbone.Collection.extend({
defaults: {
model: Field
},
model: Field,
url: 'http://localhost:8080/backbonejs/myjsoncollection.json',
initialize: function() {
console.log('FieldCollection init.');
},
/* parse: function(response) {
console.log(response);
return response;
}*/
});
var ListView = Backbone.View.extend({
el: '#app-container',
initialize: function() {
_.bindAll(this,"render");
console.log('ListView init.');
this.counter = 0;
var jsonfield = new FieldCollection();
jsonfield.fetch();
this.render(jsonfield);
},
render:function(collection){
_.each(collection, function(model){
console.log(model.get('name'));
});
_.each(function(model){
console.log(model.get('name'));
console.log(model.get('img'));
},this);
}
});
var listView = new ListView();
});
The parse function is optional, you only need to implement it, if anything special should happen after you receive the data from the server. To isolate possible sources of errors, I would simplify your approach first by not connecting to your server. Please run the following code:
var Field = Backbone.Model.extend({});
var FieldCollection = Backbone.Collection.extend({
model: Field,
});
var ListView = Backbone.View.extend({
el: '#app-container',
initialize: function() {
this.collection = new FieldCollection();
this.collection.add([{name:'name1',img:'img1'},{name:'name2',img:'img2'}]);
this.render(this.collection);
},
render(collection){
collection.each(function(model){
console.log(model.get('name')+' '+model.get('img'));
},this);
});
If this works, apply the following 2 changes:
Change the collection to include the url:
var FieldCollection = Backbone.Collection.extend({
model: Field,
url='http://localhost:8080/backbonejs/myjsoncollection.json'
});
Change the initialize function of the View to do the fetch:
initialize: function() {
this.collection = new FieldCollection();
this.collection.fetch();
this.render(this.collection);
},
Please run the simplified version first, if that works the extended version.

Using Event Aggregator to load a view with different model in backbone js

I am new to backbone.js started with backbone a week ago. I had to make a demo. The main idea behind it is when the page is loaded, I need to show the courses,and by default the students list for the first course in the list. Here is the code to display the course list which is in course.js file
//Model
var Course = Backbone.Model.extend({
urlRoot: '/api/courses/',
idAttribute: 'Id',
defaults:{
Id: null,
Name: ""
},
validate: function (attr) {
if (!attr.Name)
return "Name is required";
}
});
var Courses = Backbone.Collection.extend({
model: Course,
url: '/api/courses'
});
//Views
var CourseList = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection.on('reset', this.renderAll, this);
this.collection.on('add', this.render, this);
this.collection.fetch();
_.bindAll(this, 'renderAll', 'render');
return this;
},
renderAll: function () {
this.collection.each(this.render);
$('#spnStdntCourseName').text('Students Enrolled in ' + this.collection.at(0).get("Name"));
},
render: function (model) {
var item = new CourseItem({ model: model });
this.$el.append(item.el);
},
events: {
"click #btnAddCourse": "createNewCourse",
"keypress #txtNewCourse": "createOnEnter"
},
createOnEnter: function (e) {
if (e.keyCode == 13) {
this.createNewCourse();
}
},
createNewCourse: function () {
this.collection.create({ Name: this.$el.find('#txtNewCourse').val() });
this.$el.find('#txtNewCourse').val('');
}
});
var CourseItem = Backbone.View.extend({
tagName: 'li',
className: 'courseli',
events: {
'click .remove': 'deleteItem',
'click .edit': 'showEdit',
'click': 'courseClicked'
},
initialize: function () {
this.template = _.template($('#course').html()),
this.model.on('change', this.render, this);
this.render();
},
render: function () {
var html = this.template(this.model.toJSON());
this.$el.html('').html(html);
},
courseClicked: function () {
$('#spnStdntCourseName').text('Students Enrolled in ' + this.model.get("Name"));
Vent.trigger('studentDetails',"how to load student list from here based on courseID...?");
},
showEdit: function (event) {
event.preventDefault();
Vent.trigger('edit', this.model);
},
deleteItem: function () {
this.model.destroy();
this.remove();
}
});
var CourseEdit = Backbone.View.extend({
el: '#courseEdit',
events: {
'click #save': 'save',
'click #cancel': 'cancel'
},
initialize: function () {
_.bindAll(this, 'render', 'save');
Vent.on('edit', this.render);
this.template = _.template($('#courseEditTemplate').html())
},
render: function (model) {
var data, html;
this.model = model;
data = this.model.toJSON();
html = this.template(data);
this.$el.html(html)
.show()
.find('#name')
.focus();
this.model.on('error', this.showErrors, this);
},
save: function (event) {
var self = this;
this.model.save({
'Name': this.$el.find('#name').val()
}, {
success: function () {
alert('Saved!');
if (!window.courses.any(function (course) {
return course.get('Id') === self.model.get('Id');
})) {
window.courses.add(self.model);
}
self.$el.hide();
}
});
},
cancel: function () {
this.$el.hide();
},
showErrors: function (model, error) {
var errors = '';
if (typeof error === 'object') {
errors = JSON.parse(error.responseText).join('<br/>');
alert(errors);
}
else {
alert(error);
}
}
});
var Vent = _.extend({ }, Backbone.Events);
window.courses = new Courses();
$(function () {
var edit = new CourseEdit(),
list = new CourseList({
collection: window.courses,
el: '#coursesList'
});
});
Please take a look at the 'courseClicked' function inside CourseItem View, it is supposed to load the students list when a course item is clicked.
Now I have my Student model and views in students.js as below
var Student = Backbone.Model.extend({
urlRoot: '/api/students/',
idAttribute: 'Id',
defaults: {
Id: null
},
validate: function (attr) {
if (!attr.Name)
return "Name is required";
}
});
var Students = Backbone.Collection.extend({
model: Student,
url: '/api/students'
});
//Views
var StudentList = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection.on('reset', this.renderAll, this);
this.collection.on('add', this.render, this);
this.collection.fetch({ data: $.param({ courseId: 11 }) });
_.bindAll(this, 'renderAll', 'render');
return this;
Vent.on('studentDetails', this.render);
},
renderAll: function () {
this.collection.each(this.render);
},
render: function (model) {
var item = new StudentItem({ model: model });
this.$el.append(item.el);
},
events: {
"click #btnAddStudent": "createNewStudent",
"keypress #txtNewStudent": "createOnEnter"
},
createOnEnter: function (e) {
if (e.keyCode == 13) {
this.createNewStudent();
}
},
createNewStudent: function () {
this.collection.create({ Name: this.$el.find('#txtNewStudent').val() });
this.$el.find('#txtNewStudent').val('');
}
});
var StudentItem = Backbone.View.extend({
tagName: 'li',
className: 'studentli',
events: {
'click .remove': 'deleteItem',
'click': 'studentClicked'
},
initialize: function () {
this.template = _.template($('#student').html()),
this.model.on('change', this.render, this);
this.render();
},
render: function () {
var html = this.template(this.model.toJSON());
this.$el.html('').html(html);
},
studentClicked: function () {
var Id = this.model.get("Id");
},
deleteItem: function () {
this.model.destroy();
this.remove();
}
});
window.students = new Students();
$(function () {
var studentDetails = new StudentList({
collection: window.students,
el: '#studentsList'
});
});
so inside document.ready I have studentDetails variable which loads the students list.Here is my problem as of now I have loaded the students list on page load by passing some hard code parameter inside fetch like below
this.collection.fetch({ data: $.param({ courseId: 11 }) });
but what I need to show is, the student list for the first course in the courselist view when the page is loaded, and in later stages, the student list for each and every course item clicked.For that purpose if you can remember in the "courseClicked" function inside "CourseItem" view in course.js, I have used
Vent.trigger('studentDetails',"how to load student list from here based on courseID...?");
studentDetails is the var that I have initialised in students.js(in the code above) like this
window.students = new Students();
$(function () {
var studentDetails = new StudentList({
collection: window.students,
el: '#studentsList'
});
});
So when I trigger the studentDetails I defnitely be needing the student model inside my courseClicked function,which is not available in that context. I beleive you guys understood my problem from the above explanation. So how do I fix this...? Is the approach I followed wrong..? Any good alternative,need suggestions. Hope there is not too much noise in the question.
EDIT
var CourseList = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.students = new Students();
var studentList = new StudentList({
collection: this.students,
el: '#studentsList'
});
this.collection.on('reset', this.renderAll, this);
this.collection.on('add', this.render, this);
this.collection.fetch();
_.bindAll(this, 'renderAll', 'render');
return this;
},
renderAll: function () {
this.collection.each(this.render);
$('#spnStdntCourseName').text('Students Enrolled in ' + this.collection.at(0).get("Name"));
this.students.fetch({ data: $.param({ courseId: this.collection.at(0).get("Id") }) });
},
render: function (model) {
this.$el.html("");
var item = new CourseItem({ model: model, students: this.students});
this.$el.append(item.el);
}
})
I have made following changes
1.students in collection to this.students(inside initialize of "CourseList" view) in the below code
initialize: function () {
this.students = new Students();
var studentList = new StudentList({
collection: this.students,
el: '#studentsList'
});
2.I have fetched the students inside renderAll function instead of render function because for every course item that is fetched the student is also fetched.I mean if there are 6 courses i get to see the students for course 0 in the collection 6 times
renderAll: function () {
this.collection.each(this.render);
$('#spnStdntCourseName').text('Students Enrolled in ' + this.collection.at(0).get("Name"));
this.students.fetch({ data: $.param({ courseId: this.collection.at(0).get("Id") }) });
SubQuestion
In the "CourseList" we have initialize function as below
initialize: function () {
this.students = new Students();
var studentList = new StudentList({
collection: this.students,
el: '#studentsList'
});
The studentsList el is as below
<div id="studentsList" class="box">
<div class="box-head">
<h2 class="left">
<span id="spnStdntCourseName"></span>
</h2>
</div>
<div>
<input type="text" id="txtNewStudent" placeholder="Add New Student" />
<button id = "btnAddStudent">+ Add</button>
</div>
</div>
whenever I do this.$el.html("") inside render function of StudentList view like below
var StudentList = Backbone.View.extend({
tagName: 'ul',
render: function (model) {
this.$el.html("");
var item = new StudentItem({ model: model });
this.$el.append(item.el);
},
......
I loose the button and textbox elements inside the studentsList el, and the ul is not shown when I view source code in my browser which I mentioned as tagName, but I do see li which is tagName for studentItem view.Can you say what I am doing wrong
Thanks for our patience
First, you want to let the CourseList view to keep track of a Students collection as well as a StudentList. The Students collection will be passed into each CourseItem view to fetch. After it renders all CourseItem, it will tell the Students collection to fetch the first course's students.
var CourseList = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.students = new Students();
var studentList = new StudentList({
collection: students,
el: '#studentsList'
});
this.collection.on('reset', this.renderAll, this);
this.collection.on('add', this.render, this);
this.collection.fetch();
_.bindAll(this, 'renderAll', 'render');
return this;
},
render: function (model) {
this.$el.html("");
var item = new CourseItem({ model: model, students: this.students});
this.$el.append(item.el);
this.students.fetch({ data: $.param({ courseId: 0 }) }); // fetch the first
},
...
})
The CourseItem will store the Students collection, and on being clicked, fetch the correct students using its model's id.
var CourseItem = Backbone.View.extend({
...
initialize: function() {
this.students = this.options.students;
},
...
courseClicked: function () {
$('#spnStdntCourseName').text('Students Enrolled in ' + this.model.get("Name"));
var courseId = this.model.id;
this.students.fetch({ data: $.param({ courseId: courseId }) });
},
...
})
In StudentList view, you don't let it fetch by itself.
var StudentList = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection.on('reset', this.renderAll, this);
this.collection.on('add', this.render, this);
_.bindAll(this, 'renderAll', 'render');
return this;
},
...
render: function() {
this.$el.html(""); // Reset the view for new students
var item = new StudentItem({ model: model });
this.$el.append(item.el);
}
})
Then in your main script:
window.courses = new Courses();
$(function () {
var courseList = new CourseList({
collection: window.course,
el: '#courseList'
});
});
DISCLAIMER: Untested codes.

Resources