2
var ListView = Backbone.View.extend({
    el: $('hello'),
    initialize: function() {
        var stuff = new FieldCollection();
        var output;
        stuff.parse();
        stuff.fetch({
            success: function (collection, response) {
                console.log(response);
                output=response;
                return response;
             }
        });
        this.render(output);
   },
   render:function(output){
        console.log(output);
        $(this.el).append("<button id='add'>hiii</button>");
        $(this.el).append("<button id='removeAll'>Remove all list item</button>");
    }
});

ここで私はoutput変数の応答の値をキャッチしようとしています...しかしそれは「未定義」になります。私が間違っているアイデアはありますか?

4

2 に答える 2

5

このfetchメソッドは非同期であるため、output使用するまでに変数が割り当てられることはありません。render代わりに、success-callback内に呼び出しを入れてみてください。

var self = this;
stuff.fetch({
        success: function (collection, response) {
            console.log(response);
            output=response;
            self.render(output);
            return response;
         }
    });
于 2012-08-22T06:46:42.063 に答える
0

dbasemansソリューションは、セットアップを考慮すると正しいです。ただし、イベントハンドラーを「リセット」イベントにバインドしたいと思います。これは、フェッチの前に発生する必要があります。これはよりクリーンであり、アプリケーションの実行時に後でさらにフェッチする場合にも機能します。

于 2012-08-22T16:17:38.403 に答える