変数に格納されたJSONから、show: function(id)
という名前のルータ関数から現在のIDの名前を取得できます。しかし、JSON変数を使用する代わりにURLからコレクションを取得すると、未定義のTypeErrorが返されます。私が見てきた何バックボーン:ルータのURLからのフェッチは未定義ですが、コレクションがJSONを変数から取得すると機能します
console.log(this.collection.get(id).get('name'));
は、私はJSON変数を使用する場合show function
が正常に動作しますが、私はURLからフェッチするとき、fetch
が成功した後show function
が実行されるということです。
私は間違っていますか?なぜURLからのフェッチが未定義になるのですか?どうすればそれを動作させることができますか?
次のコードは架空のもので、コードの関連部分のみを示しています。コードブロックの最後の2つのケースを参照してください。
jsFiddle here
// Data 1 with variable
var heroes = [
{"id": "1", "name": "Batman"},
{"id": "2", "name": "Superman"},
];
// Data 2 from url: http://example.com/heroes.json
[
{"id": "1", "name": "Batman"},
{"id": "2", "name": "Superman"},
];
HeroesCollection = Backbone.Collection.extend({
model: HeroesModel,
url: 'http://example.com/heroes.json'
});
HeroesRouter = Backbone.Router.extend({
// I use two shows to graphic this example
routes: {
'': 'index',
':id': 'show'
},
initialize: function(options) {
this.collection = options.collection;
this.collection.fetch();
// this.collection.fetch({async:false}); this fixes my problem, but I heard it is a bad practice
},
index: function() {
},
show: function(id) {
console.log(this.collection.get(id).get('name'));
// Case #1: When Collection loads from a Variable
// id 1 returns: 'Batman'
// Case #2: When Collection fetchs from URL, id 1 returns:
// TypeError: this.collection.get(...) is undefined
}
});
// Case #1: collection loads JSON from a variable
var heroesCollection = new HeroesCollection(heroes);
// Case #2: collection loads JSON with fetch in router's initialize
// var heroesCollection = new HeroesCollection();
var heroesRouter = new HeroesRouter({collection: heroesCollection});
アプリケーションはどのように ':id'と一致するルートにナビゲートしますか? –
@TJナビゲートする一般的な方法は、各アイテムがそのIDにリンクするインデックスページからです。ナビゲートする別の方法は、正確なURLをIDで貼り付けることです。 –
私は上記のコードをどのように/いつ行っているのか聞いています。フェッチが完了する前にアドレスバーに直接IDを入力すると、明らかに機能しなくなり、そのようなことを処理する必要があります。それはあなたがやっていることですか?フェッチされたデータを表示するビューはどこに作成されていますか? –