1

私は正しいことをしていると信じているバックボーンビュー(以下を参照)を持っています

Index = Backbone.View.extend({
render: function() {
        var activities = new Activities();
        activities.fetch();
        var tpl = Handlebars.compile($("#activities-template").html());
        $(this.el).html(tpl({activities: activities.toJSON()}));
        return this;
      }
});

Chrome JSコンソールでrender()関数の各行を実行すると、渡した要素で期待どおりの結果が得られ、テンプレート出力が入力されます。ただし、以下を使用してこれを実行すると

var i = new Index({el: $("body")})
i.render()

「i。$el」は完全に空です。HTMLはコンソールのようにレンダリングされません。なぜ何かアイデアはありますか?

4

1 に答える 1

3

fetchはAJAX呼び出しであるため、activities.toJSON()これを行うときにデータが提供される保証はありません。

activities.fetch();
var tpl = Handlebars.compile($("#activities-template").html());
$(this.el).html(tpl({activities: activities.toJSON()}));

コンソールでコードを実行すると、AJAX呼び出しで、を使用する前に何かを返す時間が得られる可能性がありますactivities

次の2つのことを行う必要があります。

  1. が空の場合は、テンプレートを修正して、適切な処理(たとえば、読み込み中のメッセージを表示するなど)を実行します。activities
  2. renderビューをコレクションの"reset"イベントに添付します。

    initialize: function() {
        // Or, more commonly, create the collection outside the view
        // and say `new View({ collection: ... })`
        this.collection = new Activities();
        this.collection.on('reset', this.render, this);
        this.collection.fetch();
    },
    render: function() {
        var tpl = Handlebars.compile($("#activities-template").html());
        this.$el.html(tpl({activities: this.collection.toJSON()}));
        return this;
    }
    

私もに切り替えました、 Backboneがすでにあなたに与えるときthis.$elは必要ありません。$(this.el)this.$el

于 2012-09-15T17:38:22.973 に答える