1

私は、1週間前にbackboneで始めた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」関数を見てください。コース項目がクリックされたときに学生リストをロードすることになっています。

これで、以下のように Student.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変数があります。これが現在の私の問題です。以下のようにフェッチ内にハードコード パラメータを渡すことで、ページの読み込み時に学生リストをロードしました。

 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 で初期化した変数です

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.以下のコードのthis.students(「CourseList」ビューの初期化内)へのコレクション内のstudents

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

2. render 関数ではなく renderAll 関数内で生徒をフェッチしました。これは、フェッチされるコース項目ごとに生徒もフェッチされるためです。つまり、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'
    });

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> 

this.$el.html("") を実行するたびに、以下のようにStudentListビューの render 関数内で

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

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

私はstudentList el内のボタンとテキストボックス要素を失い、ブラウザでtagNameとして言及したソースコードを表示するとulが表示されませんが、studentItemビューのtagNameであるliが表示されます。間違っている

お待ちいただきありがとうございます

4

1 に答える 1

5

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

免責事項: テストされていないコード。

于 2012-06-09T13:54:39.143 に答える