2

我将Mustache.jsBackbone.js一起用于我的应用程序的模板系统。我将模板存储在<script></script>块内的外部 .html 文件中。每个脚本块都有一个唯一的 ID,我用它来使用 jQuery.get() 获取模板。

所以我的视图渲染函数如下所示:

render: function(){
    $.get('templates/templates.html', function(templates) {
        try {
            var template = $(templates).filter('#tpl-MediaView').html();
            return mustache.render(template, this.model.toJSON());

            this.playlist.each(function(media) {
                var mediaView = new MediaView({model: media});
                this.$('#playlist').append(mediaView.render());
            });
        } catch(e) {
            alert(e.message);
        }
    });
}

我遇到的问题是this.model.toJSON从 $.get() 内部访问。我尝试将值分配给外部变量并将其传入。我也尝试在外部运行 return。我也尝试过使用 $.ajax()。处理此范围问题的最简单方法是什么?

- 更新 -

我应该补充一点,我收到的这段代码的错误是:

无法调用未定义的方法“toJSON”

4

1 回答 1

3

无法调用未定义的方法“toJSON”

这意味着this.model返回未定义,这意味着this不是你想的那样。可悲的是,它实际上是全局对象。任何时候你传递一个函数引用,它都会丢失上下文。

我已经尝试将值分配给外部变量并将其传入。

你?因为听起来是对的,而且这通常是如何完成的。

通常你保存this到封闭函数之外的局部变量。然后在函数中使用它而不是 self.

render: function(){
    var self = this; // or some like "var that = this"
    $.get('templates/templates.html', function(templates) {
        //...
        self.model.toJSON()
        //...
    });
}

您还可以bind针对特定上下文运行,尽管并非所有浏览器/运行时都完全支持这一点。

render: function(){
    $.get('templates/templates.html', function(templates) {
        //...
        this.model.toJSON()
        //...
    }.bind(this));
}

而且我知道您没有在这里询问 CoffeeScript,但是如果您想切换它,它有一个非常棒的功能可以解决这个问题。箭头->声明了一个普通函数,但粗箭头=>声明了一个绑定函数,它保留this了函数之外的任何内容,基本上是在var self = this无形中为你做这个把戏。所以这里的代码可以正常工作。

render: ->
    $.get 'templates/templates.html', (templates) =>
        # ...
        this.model.toJSON()
        # ...
于 2012-07-20T23:39:16.587 回答