0

バックボーンでの収集と表示

var studentmodel = Backbone.Model.extend();

    var studentcollection = Backbone.Collection.extend({
model : studentmodel,
url : 'http://localhost/bb/data.JSON',
parse : function(response){
    //console.log(response.data);
    return response.data;
    //return response;
},
  });



var studentlistview = Backbone.View.extend({
    tagName : "ul",
    className : "studentlistul",
    initialize : function(){
        this.model.bind("reset", this.checkEvent,this);
        this.model.bind("add", this.checkEvent,this);
    },
      checkEvent : function(){

        $(this.el).html("");

    _.each(this.model.models, function(student){

    $(this.el).append(new studentListItemView({ model : student}).render2().el);
    }, this);

    $('#studentlistdiv').html($(this.el));

    return this;

} });

このモデルとその作業にアイテムを追加しようとすると、私の質問は、レンダー fn 内で this.model.bind("add", this.checkEvent,this) この evt が発生している間にイベント タイプを取得する方法です。checkEvent内で、イベントのタイプ、つまり追加またはリセットのどちらが発生したかを取得するにはどうすればよいですか。これは私の質問です 助けてください

4

1 に答える 1

2

バックボーン イベント ハンドラーが、どのイベントがそれをトリガーしたかを知る確実な方法はありません。これを行う代わりに:

this.model.bind("reset", this.checkEvent, this);
this.model.bind("add",   this.checkEvent, this);

必要なアクションごとに個別のハンドラーが必要です。

// A reset generally means that you want to redraw the whole thing.
this.model.bind("reset", this.render, this);

// If one model is added then you usually just want to render the
// the new one.
this.model.bind("add", this.render_one, this);

そして、あなたrenderは次のようになります:

this.$el.empty();
this.collection.each(this.render_one, this);
return this;

私がここにいる間、いくつかの追加事項:

  1. バックボーン ビューには既に jQuery バージョンのthis.elinthis.$elがあるため、必要はありません。$(this.el)使用するだけthis.$elです。
  2. バックボーン ビューは、それらが処理するのと同じ方法でcollectionオプションmodelを処理します。したがってnew View({ collection: c })、ビューには自動的にthis.collection. コレクションがある場合は を使用collectionし、モデルがある場合はmodel;を使用します。正確な名前を使用すると、混乱が少なくなります。
  3. バックボーン コレクションには、多数のUnderscore メソッドが既に混在しているため、this.collection.each(...)代わりに_(this.collection.models, ...).
于 2012-11-23T17:34:57.677 に答える