2011-12-28 19 views
0

私は、バックボーンズ・ジャズのものを書いて、どこでもっとうまく理解できるようにしています。私はサイトを持っていて、ページコンテンツを含むコレクションをロードしています。backbone.js初心者コレクション

JSONデータは、私のルータ上の(PID、名前、タイトル、内容)に戻ってくるデフォルトは

defaultRoute: function (actions) 
{ 
    this.showInfo('food'); 
}, 
showInfo: function (id) 
{ 
    var view = new ContentView({ model: this._items.at(id) }); 
    $(".active").removeClass("active"); 
    $("#" + id).addClass("active"); 
    view.render(); 
} 

である私は、この「新ContentView({モデルにIDの代わりに0を置く場合:この._items.atは(0)})」私は、コレクション内の最初の項目を取得し、私はビューでこれを行う場合:

var ContentView = Backbone.View.extend({ 
    el: $('#content'), 

    render: function() 
    { 
     this.el.empty(); 
     $(this.el).append(this.model.attributes.content); 
     return this; 
    } 
}); 

私は、コンテンツが完全に表示されますが、もちろん、コンテンツIではないかもしれない取得します欲しい

名前== "food"に基づいてコレクションから選択することは可能ですか?これは愚かな質問のように思えるが、私はすべての単純

確認イム不足しているものを見て、イムの上にクロールしている場合、私はID番号にコンテンツをマッピングする必要がありますする必要はいけないことはデシベル

申し訳への格納の目的に反しそれは

var NavigationRouter = Backbone.Router.extend({ 
    _data: null, 
    _items: null, 
    _view: null, 

    routes: { 
     "p/:id": "showInfo", 
     "*actions": "defaultRoute" 
    }, 
    initialize: function (options) 
    { 
     var _this = this; 
     $.ajax({ 
      url: "page_data.php", 
      dataType: 'json', 
      data: {}, 
      async: false, 
      success: function (data) 
      { 
       _this._data = data; 
       _this._items = new ItemCollection(data); 
       _this._view.render(); 
       Backbone.history.loadUrl(); 
      } 

     }); 

     return this; 
    }, 
    defaultRoute: function (actions) 
    { 
     this.showInfo('home'); 
    }, 
    showInfo: function (id) 
    { 
     var view = new ContentView({ model: this._items.at(id) }); 
     $(".active").removeClass("active"); 
     $("#l_" + id).parent().addClass("active"); 
     view.render(); 
    } 
}); 

答えて

2

バックボーンはそのCollectionsUnderscore's機能の束をミックスできます場合には、ここで私の完全なNavigationRouterコードです。

あなたはname === 'food'コレクションにモデルを見つけたい場合は、あなたが行うことができますので:サイドノートとして

var foodModel = this._items.find(function(model) { 
    return model.get('name') === 'food'; 
}); 
// this will set foodModel to the first model whose name is 'food' 

を、あなたのレンダリング機能でemptyを呼び出す必要はありませんが、できるのと同じ:

render: function() { 
    $(this.el).html(this.model.get('content')); 
    return this; 
} 

jQueryのhtml機能は、ちょうどあなたが渡したHTML文字列を持つ要素の内容を置き換える

+0

だから私は作成する必要があります。新しいvar homeModelなど各ページのために私はこのshow.initがNavigationRouterの外で定義されていないので、show infoの中でルーティングするつもりです – Ehask

+0

アンダースコアの 'find'関数を使って新しいモデルを作成していません。 'this._items'に既に存在するモデルを見つけ、そのモデルへの参照を保存するだけです。次に、それを使って、既存のビューに渡したり、新しいビューに渡したりすることができます。 – satchmorun

+0

ありがとう!! – Ehask