1

我是新来的主干.js 一周前开始使用主干。我不得不做一个演示。它背后的主要思想是当页面加载时,我需要显示课程,默认情况下,学生列表中的第一门课程。这是显示course.js文件中的课程列表的代码

//模型

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

//视图

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

请查看CourseItem视图中的“courseClicked”函数,它应该在单击课程项目时加载学生列表。

现在我在students.js中有我的学生模型和视图,如下所示

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

//视图

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

所以在 document.ready 我有studentDetails变量,它加载学生列表。这是我现在的问题,我已经通过在 fetch 中传递一些硬代码参数来加载学生列表,如下所示

 this.collection.fetch({ data: $.param({ courseId: 11 }) });

但我需要展示的是,当页面加载时,课程列表视图中第一门课程的学生列表,以及在稍后阶段,点击的每个课程项目的学生列表。为此,如果你记得course.js 中“CourseItem”视图中的“courseClicked”函数,我使用过

 Vent.trigger('studentDetails',"how to load student list from here based on courseID...?");

studentDetails 是我在students.js中初始化的var(在上面的代码中),如下所示

window.students = new Students();
$(function () {
var studentDetails = new StudentList({
    collection: window.students,
    el: '#studentsList'
});      
}); 

因此,当我触发 studentDetails 时,我肯定需要我的 courseClicked 函数中的学生模型,这在该上下文中不可用。我相信你们从上面的解释中理解了我的问题。那么我该如何解决这个问题......?我遵循的方法是否错误..?任何好的选择,需要建议。希望问题中没有太多噪音。

编辑

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

我做了以下更改

1.students in collection to this.students(inside initialize of "CourseList" view) 在下面的代码

initialize: function () {
    this.students = new Students();
    var studentList = new StudentList({
        collection: this.students,
        el: '#studentsList'
    });

2.我在renderAll函数而不是render函数中获取了学生,因为对于获取的每个课程项目,学生也被获取。我的意思是如果有6门课程,我可以在集合中看到学生0课程6次

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

子问题

在“CourseList”中,我们有如下初始化函数

 initialize: function () {
    this.students = new Students();
    var studentList = new StudentList({
        collection: this.students,
        el: '#studentsList'
    });

学生名单如下

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

每当我这样做时。$el.html("") 在StudentList视图的渲染函数中,如下所示

var StudentList = Backbone.View.extend({
tagName: 'ul',

render: function (model) {
this.$el.html("");
    var item = new StudentItem({ model: model });
    this.$el.append(item.el);
},
......

我松开了studentsList el中的按钮和文本框元素,当我在浏览器中查看我提到的tagName的源代码时没有显示ul,但我确实看到li是studentItem视图的tagName。你能说我是什么做错事

感谢我们的耐心

4

1 回答 1

5

首先,您想让CourseList视图跟踪Students集合以及StudentList. 该Students集合将被传递到每个CourseItem视图以获取。渲染完 all 后CourseItem,它会告诉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
  },
  ...
})

CourseItem存储Students集合,并在被点击时使用其模型的 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 }) });
  },
  ...
})

StudentList视图中,您不要让它自己获取。

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

然后在你的主脚本中:

window.courses = new Courses();

$(function () {
   var courseList = new CourseList({
        collection: window.course,
        el: '#courseList'
    });
});

免责声明:未经测试的代码。

于 2012-06-09T13:54:39.143 回答