2013-01-20 209 views
0

我正在嘗試使用require.js,AMD和模板的handlebars構建一個Backbone應用程序。 這是我的索引視圖的代碼。將'this'引用傳遞給Backbone函數

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; 
}); 

這裏一切都按照原理進行工作。但是現在我想要一個輔助函數計數,它將返回集合中模型的數量。這樣我可以在handle bar template中使用{{count}}來打印類似的東西。 'There are 8 questions'。但是我的範圍有問題。

裏面count功能這是指window但不是collection。我如何能夠在count內部獲得question collection的參考。我打算在我的應用程序中使用這些輔助函數。所以需要一些可靠的方法來做到這一點。

THanks。

+0

爲什麼你傳遞視圖模板函數?爲什麼不給模板函數視圖的數據(即集合),以至於你甚至不需要幫助器? –

+0

另一種選擇是將count函數放入集合中,並將其作爲this.collection.count()引用。 –

+0

@DennisRongo但你將如何在模板中使用?我想在像{count}'這樣的模板中使用它。 – Subash

回答

4

您可以使用 'bindAll' 功能從Underscore.js如下:

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

基本上,它取代你的 '計數' 的方法有類似的代碼如下:

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() 
    }); 
} 
相關問題