【问题标题】:Pass 'this' reference to Backbone function将“this”引用传递给 Backbone 函数
【发布时间】:2013-01-20 02:17:40
【问题描述】:

我正在尝试使用 require.js、AMD 和车把作为模板构建一个 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;
}); 

这里一切都按预期工作。但现在我想要一个辅助函数 count 来返回集合中模型的数量。这样我就可以在我的handle bar template 中使用{{count}} 来打印类似的东西。 'There are 8 questions'。但我的范围有问题。

在count 函数中,这指的是window,而不是collection。我将如何在count 中以question collection 引用此内容。我计划在我的应用程序中使用许多这些辅助功能。所以需要一些可靠的方法来做到这一点。

谢谢。

【问题讨论】:

  • 为什么要将视图传递给模板函数?为什么不给模板函数视图的数据(即集合),这样你甚至不需要帮助器?
  • 另一种选择是将计数函数放入集合中,并将其称为 this.collection.count()。
  • @DennisRongo 但是您将如何在模板中使用它?我想在 {count} 这样的模板中使用它。
  • 通常的做法是说this.template({ collection: this.collection.toJSON() })之类的东西,然后你在模板中的{{collection}}中有一个简单的数组,你可以问它有多长而不用担心方法绑定。跨度>
  • 您可以将您的收藏和计数作为一个对象传递到您的模板中。例如,this.template{ coll: this.collection, count: this.collection.count()}。我建议将计数包含在集合中的原因是,它将视图从具有特定集合中解放出来。这使您的视图灵活且可重复用于不同的集合。

标签: backbone.js requirejs handlebars.js


【解决方案1】:

您可以使用 Underscore.js 中的“bindAll”函数,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-07
    • 2016-12-11
    • 2014-03-05
    • 2020-10-10
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多