【问题标题】:Using Event Aggregator to load a view with different model in backbone js使用事件聚合器在骨干 js 中加载具有不同模型的视图
【发布时间】:2012-06-09 07:33:50
【问题描述】:

我是新来的主干.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中有我的Student模型和视图,如下所示

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) in the following code

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。你能说我做错了什么

感谢我们的耐心

【问题讨论】:

  • 我会假设我可以GET /api/students/:courseId 获取该课程ID 中的所有学生?
  • 抱歉,没关系,您使用$.param 来获取学生。
  • 关于清理东西。最好使用模板仅呈现学生,而不是使用现有元素附加到 DIV。这样您就可以替换该模板的内容。

标签: backbone.js asp.net-mvc-4


【解决方案1】:

首先,您想让CourseList 视图跟踪Students 集合以及StudentList。 Students 集合将被传递到每个 CourseItem 视图中以获取。渲染完所有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'
    });
});

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

【讨论】:

  • 这就像一个魅力,但一个问题是当我点击课程项目时,我看到点击课程的学生以及上一门课程......它是否与幽灵视图有关.. .?
  • 还有一个问题 :) 你能说一下我如何在页面加载后立即向学生展示第一个课程项目..?
  • 这里有重复的代码,对吧..?在我上面提到的 student.js 文件中,在 document.ready 中我编写了与现在在“courseClicked”中编写的相同代码:|。
  • 我是否必须编写 courseList.fetch() 因为我已经在“CourseList”视图的初始化函数中提到了它,并且删除它会显示我的课程
  • 对不起,我是AFK。看到重复学生的第一个问题是因为 CourseList 视图未重置。需要在附加任何 CourseItem 视图之前清除该视图。您不想在 document.ready 中初始化学生,因为您不知道要获取哪些学生。让CourseItem 视图处理它。是的,我没有仔细阅读CourseList,因此那里重复了courseList.fetch。对不起。我还在考虑加载第一门课程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
相关资源
最近更新 更多