backbone - 1 model - 2 views

by knunery

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<div id="view1">

</div>
<div id="view2">

</div>
<input class="removeStudent" type="button" value="click me" />

JavaScript

Student = Backbone.Model.extend({
    defaults: {
        firstName: "firstName",
        lastName: "lastName",
        gpa: 0.0
    }
});
Class = Backbone.Collection.extend({
    model: Student,
    initialize: function() {

    }
});



View1 = Backbone.View.extend({
    tagName: "li",
    initialize: function(){
        this.model.bind('destroy', this.remove, this);       
        //this.model.on('remove', this.remove, this); 
    },
    template: _.template("<%= firstName %> <%= lastName %>"),
    render: function() {
        //console.log(this.template(this.model.toJSON()) );
        this.$el.html(this.template(this.model.toJSON()));
        console.log(this.$el.html());
        return this;
    }
});

StudentListView1 = Backbone.View.extend({
    tagName: "ul",
    initialize: function() {
        this.collection.on('add', this.addOne, this);
        this.collection.on('reset', this.render, this);
    },
    addOne: function(student) {
        var studentView1 = new View1({
            model: student
        });
        this.$el.append(studentView1.render().el);
    },
    render: function() {
        this.collection.forEach(this.addOne, this);
    }
});

View2 = Backbone.View.extend({
    tagName: "li",
    template: _.template("<%= lastName%>"),
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

var StudentListView2 = Backbone.View.extend({
    tagName: "ul",
    initialize: function() {
        this.collection.on('add', this.addOne, this);
        this.collection.on('reset', this.render, this);
    },
    addOne: function(student) {
        var studentView2 = new View2({
            model: student
        });
        this.$el.append(studentView2.render().el);
    },
    render: function() {
        this.collection.forEach(this.addOne, this);
    }
});

var students = [{
    firstName: "Kyle",
    lastName: "Black"},
{
    firstName: "Jason",
    lastName: "Bourne"}];

var scienceClass = new...