0

我已经在本地存储中存储了一些数据。我读取本地存储上的数据

 localStorage.getItem('students');

从本地存储读取结果

 [
  {
    "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"
}
]

我正在使用主干和下划线。我想使用来自本地存储的学生 json 数据上方的下划线模板生成 html,并将其连接到一些

 <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>

我怎样才能做到这一点?另外,我希望每个列表都是一些模型或其他东西,这样当我点击它时,它允许我进入一些视图,显示学生中的所有字段。尽管我从本地获取数据,但需要创建模型或集合 -贮存?

4

1 回答 1

1

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.

于 2013-05-29T14:20:30.327 回答