0

テンプレート用のrequire.js、AMD、およびハンドルバーを使用してバックボーンアプリケーションを構築しようとしています。これが私のインデックスビューのコードです。

define([
  'jquery',
  'underscore',
  'backbone',
  'handlebars',
  'collection/questions',
  'helpers'
], function($, _, Backbone, Handlebars, QuestionsCollection, Helpers){
// Main Index View
var IndexView = Backbone.View.extend({
    el: "#content",
    template: Helpers.template('index'),

    initialize: function(){
        this.questions = new QuestionsCollection();
        this.questions.on('sync', this.render, this);
        this.questions.fetch();
    },

    render: function(){
        this.$el.html(this.template(this));
        this.questions.each(this.addQuestion, this);
        return this;
    },

    addQuestion: function(question){
        var view = new IndexView.Question({ model: question });
        view.render();
    },

    count: function(){
        console.log(this);
        return this.questions.length;
    }
});

// Individual Question View
IndexView.Question = Backbone.View.extend({
    render: function(){
        // console.log(this.model);
    }
});

return IndexView;
}); 

ここでは、すべてが期待どおりに機能しています。しかし今、コレクション内のモデルの数を返すヘルパー関数 count が必要です。そうすれば、次のようなものを印刷するため{{count}}に使用できます。. しかし、私はスコープに問題があります。handle bar template'There are 8 questions'

count関数内では、これは を参照しますが、 は参照しwindowませんcollectioncountとして内部でこれへの参照を取得するにはどうすればよいですかquestion collection。アプリでこれらのヘルパー関数の多くを使用する予定です。そのため、しっかりとした方法が必要です。

ありがとう。

4

1 に答える 1

4

Underscore.jsの「 bindAll」関数は次のように使用できます。

initialize: function () {
    _.bindAll(this, 'count');
    // your initialize code
}

基本的に、'count'メソッドを次のようなコードに置き換えます。

var thisReference = this;
var originalCount = this.count;

this.count = function () {
    originalCount.apply(thisReference, Array.prototype.slice.call(arguments));
};

つまり、元の「this」参照を保存し、「count」メソッドが呼び出されたときにそれを渡します。

現在、ブラウザにはこのイディオムのサポートが組み込まれています(を参照 Function.bind)。

countそれでも、この場合は、をテンプレート変数として渡す方がよいでしょう。

render: function () {
    this.template({
        count: this.count()
    });
}
于 2013-01-20T03:11:09.123 に答える