我将Mustache.js与Backbone.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”