2012-01-14 8 views
4

私は非常に簡単にすべきことがあります。私は新しいコレクションを作成し、それをレンダリングに渡してコレクションモデルをページに追加したいと思います。これは、エラーを返し backbone.jsコレクションが.eachに応答していない

 
get_results: function(){ 
    $.getJson(this.url,function(response){ 
     this.search_results = new Kitchon.Collections.searchList(response); 
     console.log(this.search_results); 
     this.search_results.each(this.render_match); 
    } 
}, 
render_match: function(model){ 
    console.log(model) 
}, 

Uncaught TypeError: undefined is not a function

私のコレクションは、私は物事の多くを試してみた

 
_byCid: Object 
_byId: Object 
_onModelEvent: function() { [native code] } 
_removeReference: function() { [native code] } 
length: 7 
models: Array[7] 
__proto__: o 

通常の構造を持っているが、突き出し一つのことは、多分私はなければなりませんでした this.search_results.models.each(this.render_match);を実際の配列として渡しますが、それを行うと、私はUncaught typeError: Object [object Object],[object Object],...

答えて

6

あなたは、各メソッドのコールバック関数が呼び出された実行コンテキストを失う

使用_.bind(this.render_match, this)render_matchは右文脈

を持っていることを確認するためにコールバックを渡すと、あなたがラップしていなかったので、あなたがエラーを取得し、 getJsonメソッドのコールバック関数もありません。そこにアンダースコアbindメソッドも使用する必要があります。私がseee何から...多かれ少なかれ、次のようになりますここでhttp://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/

正しいコードを試してみてください

get_results: function(){ 

    $.getJSON(this.url, _.bind(function(response){ 

     this.search_results = new Kitchon.Collections.searchList(response); 
     console.log(this.search_results); 
     this.search_results.each(_.bind(this.render_match, this)); 
    }, this)); 
}, 
render_match: function(model){ 

    console.log(model) 
}, 
もののを -

は、あなたはjavascript thisとどのようにそれを飼いならすために約ビットをお読みください - 私がここに示したコードは、モデルまたはコレクションのいずれかであると仮定します。ビューのレンダリングを処理しています。モデルとコレクションは、データの保存と解析のみを目的としています。すべてのレンダリングと制御アプリケーションフローは、ルータの助けを借りてビュー(コントローラ)で行う必要があります。

+1

おかげでトム、私はそれが何とか「これ」で迷子になっていたことを知っていましたが、私はそれを働かせる方法がわかりませんでした。 Yehudaからの記事は素晴らしい追加です。これを検索して関連性の高い結果を得るのは難しいです。 – pedalpete

-1

ちょうど(私がBACKBONE.JSについて何も知らない)、ここで刺しを取るが、これはあなたが探しているものではありません。

$.each(this.search_results, function(index, value) { 
    alert(index + ': ' + value); 
}); 

グッドラック!

+1

BACKBONE.JSはコレクションにunderscore.js方法の多くをマッピングしている - あなたがする必要はありません、あなたが手元にunderscorejsを持っている場合、それぞれのjQueryを使用すべきではありません - 実装が少し早い+ this.search_resultsは実際のArrayではなく、Backbone.Collectionインスタンスです。モデルを繰り返し処理したい場合は、コレクションの 'models'属性にアクセスする必要があります。 –

3

$.getJsonthisの参照を変更します。 jqueryの多くのメソッドがそうしているので、this.render_matchの値はnullです。 eachにはNULLが渡され、失敗します。

これを解決するには、$.getJsonの前にこれを参照して(var _this = this;など)、thisの代わりに使用してください。コードは以下のようにする必要があります。

get_results: function(){ 
    var _this = this; 
    $.getJson(this.url,function(response){ 
     _this.search_results = new Kitchon.Collections.searchList(response); 
     console.log(_this.search_results); 
     _this.search_results.each(_this.render_match); 
    } 
}, 
render_match: function(model){ 
    console.log(model) 
}, 
+1

あなたはそれぞれのループで 'this'コンテキストをもう一度失った - 私の答えをチェックする –

関連する問題