您可以延迟 jQuery 选择器,直到您需要它:
render: function(){
var templateHtml = $(this.template).html();
_.template(templateHtml);
}
或者您可以在视图初始化时运行选择器:
initialize: function(){
this.template = _.template($(this.template).html());
}
或者,如果您真的想保留代码原样并在定义视图时让选择器评估,您可以将所有 Backbone 代码包装在一个函数中,当您想要初始化整个应用程序代码时调用该函数......例如$(function(){}
真实 HTML 页面上的 jQuery 函数,或beforeEach
Jasmine 测试中的函数:
MyApp = (function(){
var myApp = {};
myApp.MyView = Backbone.View.extend({
template: _.template($("#item-template").html())
// ...
});
return myApp;
});
然后在您的应用程序中,启动它:
$(function(){
var myApp = MyApp();
new myApp.MyView();
// ...
});
在你的茉莉花测试中:
describe("how this thing works", function(){
beforeEach(function(){
var myApp = MyApp();
this.view = new myApp.MyView();
// ...
});
});
一旦你有了这些解决方案之一,你就可以使用 Jasmine-jQuery 之类的东西来加载你的固定装置。
FWIW:我倾向于根据需要结合使用这些技术。