使用事件聚合器加载骨干JS用不同的模型视图(Using Event Aggregator to lo

2019-07-29 19:37发布

我是新来Backbone.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我有它加载学生list.Here是我的问题,因为现在我已经通过传递一些硬编码参数加载在页面载入学生名单内取像下面studentDetails变量

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

但我要表明的是,当页面加载在courselist视图中的第一门课程学生名单,并在以后的阶段,每个学生名单和clicked.For为此每门课程的项目,如果你能在记“courseClicked”功能里面course.js“CourseItem”的观点,我已经使用

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

studentDetails是我在students.js已初始化(在上面的代码中)这样的无功

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

所以,当我触发studentDetails我defnitely是需要我的courseClicked功能,这是不是在这方面可里面的学生模型。 我beleive你们从上面的描述可以理解我的问题。 那么,如何解决这个问题......? 是我跟着方法不对..? 任何一个优秀的选择,需要的建议。 望有没有问题太多的噪音。

编辑

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在收集到this.students(内侧的“CourseList”视图初始化)

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

2.我已经赚得renderAll功能,而不是渲染函数内的学生,因为所获取的学生每门课程的项目也fetched.I意思是,如果有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") }) });

SubQuestion

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

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

该studentsList EL是如下

<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埃尔内的按钮和文本框元素,当我查看我的浏览器,我作为标签名提到的源代码没有显示UL,但我确实看到李是标记名studentItem view.Can你说我是什么做错了

感谢我们的耐心

Answer 1:

首先,你要让CourseList视图跟踪A的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'
    });
});

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



文章来源: Using Event Aggregator to load a view with different model in backbone js