1

こんな感じのコレクションがあります

[
    {
        "year": 1868,
        ....
           ]
    },
    {
        "year": 1872,
        ....
    },
    {
        ...
    }
]

またはでルートを設定する方法はあります'/year/:year': 'year''/(:year)': 'year'?

メインの App ビューでルックアップ テーブルを作成してみました。これにより、年のインデックスがモデル ビューに渡されます。_.map、_.each、_.pluck、および _.where を使用してみましたが、何か間違ったことをしているに違いないと思います。

これは、どのように見えるかの非バックボーン ビューです。したがって、/(:year) に移動すると、モデル インデックスに対応するその年に直接移動します。

編集:明確にするために、基本的にはユーザーがにアクセスできるようにしたいのです/year/:yearが、:year値は特定のモデルに対応しています(上記を参照)。この場合/year/1868、 に移動すると、上記のコレクションから最初のモデルがレンダリングされます。

編集#2:これが私のアプリの外観です。

これはルーターです var router = Backbone.Router.extend({ routes: { '': 'root', 'year(/:year)': 'year' },

    root: function() {
        new App();
    },

    year: function(year) {
        new App({
            year: year
        });
    }
});

このファイルを呼び出す

define(['backbone', 'assets/js/collections/elections.js', 'assets/js/views/election.js', 'jqueryui'], function(Backbone, Elections, ElectionView, simpleSlider) {
var AppView = Backbone.View.extend({
    current_election_index: 0,
    active_btn_class: 'dark_blue_bg',
    wiki_base: 'http://en.wikipedia.org/wiki/United_States_presidential_election,_',
    started: 0,
    el: 'body',
    playback: {
        id: '',
        duration: 1750,
        status: false
    },

    initialize: function() {
        elections = new Elections();
        _.bindAll(this, 'render');
        this.listenTo(elections, 'reset', this.render);
        elections.fetch();
        this.remove_loader();
    },

    render: function () {
        if (this.started === 0) {
            this.election_year();
        }
        var view = new ElectionView({
            model: elections.at(this.current_election_index),
            election_index: this.current_election_index
        });
        this._make_slider();
        this.update_ui();
        return this;
    },

それらは必須ではないので、いくつかのメソッドを取り出しました。

4

1 に答える 1

0

典型的な解決策は次のようになります。

var AppRouter = Backbone.Router.extend({
  routes: {
    "year(/:year)" : "electionByYear"
  },

  electionByYear: function(year) {

    //all of your data, wherever you get it from
    var results = this.allElectionResults;

    //if a year parameter was given in the url
    if(year) {
        //filter the data to records where the year matches the parameter
        results = _.findWhere(results, { year: parseInt(year, 10)});
    }

    doSomething(results);

  }
});

コメントに基づいて編集:ビューがコレクションの作成を担当している場合は、上記のロジックをビューに移動し、yearパラメーターを引数としてビューに渡すだけです。

var View = Backbone.View.extend({
  initialize: function(options) {
    this.year = options.year;
  }
});

var view = new View({year:year});
view.render();

または、既存のビューを使用している場合:

view.year = year;
view.render();
于 2013-02-27T14:56:26.690 に答える