1

すぐに飛び込んで簡単な「質問」アプリを作成することでBackboneを学ぼうとしていますが、モデルやコレクションを正しく使用する方法を見つけようとして、壁に頭をぶつけてきました。迷子になったところまでコードを追加しました。コレクションを取得してJSONファイルを取り込むことはできますが( "var list = new QuestionList; list.getByCid('c0')を実行すると最初の質問が返されるようです)、更新方法がわかりません。それを使用してモデルを作成し、ビューのデータに現在のモデルを使用してから、[次へ]ボタンがクリックされたときに次の質問でモデルを更新する方法を説明します。

ここで取得しようとしているのは、ロード時にJSONをプルアップし、最初の質問を表示し、ボタンが押されたときに次の質問を表示する単純なアプリです。

誰かが私が点をつなぐのを手伝ってもらえますか?

/questions.json

[
  {
    questionName: 'location',
    question: 'Where are you from?',
    inputType: 'text'
  },
  {
    questionName: 'age',
    question: 'How old are you?',
    inputType: 'text'
  },
  {
    questionName: 'search',
    question: 'Which search engine do you use?'
    inputType: 'select',
    options: {
      google: 'Google',
      bing:   'Bing',
      yahoo:  'Yahoo'
    }
  }
]

/app.js

var Question = Backbone.Model.Extend({});
var QuestionList = Backbone.Collection.extend({
  model: Question,
  url: "/questions.json"
});

var QuestionView = Backbone.View.extend({
  template: _.template($('#question').html()),
  events: {
    "click .next" : "showNextQuestion"
  },
  showNextQuestion: function() {
    // Not sure what to put here? 
  },
  render: function () {
    var placeholders = {
      question: this.model.question, //Guessing this would be it once the model updates
    }
    $(this.el).html(this.template, placeholders));
    return this;
  }
});
4

1 に答える 1

2

明らかなように、現在の設定では、ビューは単一のモデルよりも広い範囲にアクセスする必要があります。私が見ることができる、ここでの2つの可能なアプローチ。

new QuestionView({ collection: theCollection })1)モデルではなくコレクションを(を使用して)に渡しQuestionViewます。クリックイベントでインクリメントおよび再レンダリングするインデックスを維持します。これは次のようになります。

var QuestionView = Backbone.View.extend({

  initialize: function() {
     // make "this" context the current view, when these methods are called
     _.bindAll(this, "showNextQuestion", "render");
     this.currentIndex = 0;
     this.render();
  }      
  showNextQuestion: function() {
     this.currentIndex ++;
     if (this.currentIndex < this.collection.length) {
         this.render();
     }
  },
  render: function () {
    $(this.el).html(this.template(this.collection.at(this.currentIndex) ));
  }
});

2)ルーターを設定しrouter.navigate("questions/" + index, {trigger: true})、クリックイベントを呼び出します。このようなもの:

var questionView = new QuestionView( { collection: myCollection });

var router = Backbone.Router.extend({
    routes: {
        "question/:id": "question"
    },

    question: function(id) {
        questionView.currentIndex = id;
        questionView.render();
    }
});
于 2012-10-18T21:24:36.267 に答える