2013-01-20 216 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() 
    }); 
} 
相关问题