Reputation: 113
I have stored some data on local storage. I read data on localstorage with
localStorage.getItem('students');
The read from local storage results
[
{
"studentName":"John",
"rollno":"12",
"address1":"add1",
"address2":"add2",
"city":"Jackson Height",
"state":"New York",
"zip":"0111"
},
{
"studentName":"Mohan",
"rollno":"13",
"address1":"add3",
"address2":"add5",
"city":"Mackson Height",
"state":"New york",
"zip":"004"
}
]
I am using backbone and underscore. I want to generate html as follows with underscore template from above student json data from local storage and hook it to some
<ul>
<li ><strong>Appointments</strong></li>
//I want to create list from here from student data from localstorage
<li>student name 1 rollno</li>
<li>student name 2</li>
</ul>
How can I do this? Also, i wanted each list to be some model or something so that when i click on it, it allows me to go some view that will display all fields in students.Do in need to create model or collection though i take data from local-storage?
Upvotes: 0
Views: 283
Reputation: 1453
eh... this is a little complicated if you want make every "li" as a view. This is my solution:
You need a super-view to hold the ul, and create sub-views as many as you want in this super-view.
// this is the sub view, it's stand for every student
var SubView = Backbone.View.extend({
// every student's name display in a li
template: _.template('<li><%= obj.studentName %></li>'),
// let every sub view react click event
events: {
'click': 'showDetail'
},
// draw li
render: function() {
// model will be passed in went sub view was created, and sub view append to ul
this.$el.html(this.template(this.model.toJSON())).appendTo('.ul');
},
showDetail: function() {
// here is your function to show student's detail
// note you got the student data when this view was create
// so you can refer it with this.model
}
});
// this is the super view
var SuperView = Backbone.View.extend({
// catch ul, i assume it is the only one ul exists on your page
el: $('ul'),
// run on super view was createc
initialize: function() {
// get your students
var students = localStorage.getItem('students');
// loop through students
_.each(students, function(student) {
// create sub view(li) for every student
var subView = new SubView({
// a little tricky here, wrap your student data into model
// and pass it (or say save it) in every sub view
model: new Backbone.Model.extend(student);
});
// render the sub view
subView.render();
});
}
});
after all this, just do "new SuperView()". and should be what you want.
this code is just an idea, I didn't run it actually.
Upvotes: 1