Jquery 贾斯敏赢得';在spec开始执行之前,不允许将fixture附加到DOM
在Rails 4的主干视图中,我试图让Handlebar编译一个模板。它需要在DOM中可用,然后才能编译Jquery 贾斯敏赢得';在spec开始执行之前,不允许将fixture附加到DOM,jquery,ruby-on-rails,backbone.js,jasmine,handlebars.js,Jquery,Ruby On Rails,Backbone.js,Jasmine,Handlebars.js,在Rails 4的主干视图中,我试图让Handlebar编译一个模板。它需要在DOM中可用,然后才能编译 var ItemsView = Backbone.View.extend({ template: Handlebars.compile($("[data-name=items]").html()), render: function() { this.$el.html(this.template({ items: this.collection.toJSON() }));
var ItemsView = Backbone.View.extend({
template: Handlebars.compile($("[data-name=items]").html()),
render: function() {
this.$el.html(this.template({ items: this.collection.toJSON() }));
},
initialize: function() {
this.$el = $("#items");
this.listenTo(this.collection, "change", this.render);
}
});
当我在浏览器中运行它时,Handlebars可以很好地编译,但是当我在上面运行我的Jasmine规范时--为它提供一个fixture--在主干视图开始执行之后,fixture会被加载,因此我得到,错误:您必须将字符串或Handlebars AST传递给Handlebars.compile。您传递了未定义的
——没有可编译的脚本标记(在本例中)
var ItemsView = Backbone.View.extend({
template: Handlebars.compile($("[data-name=items]").html()),
render: function() {
this.$el.html(this.template({ items: this.collection.toJSON() }));
},
initialize: function() {
this.$el = $("#items");
this.listenTo(this.collection, "change", this.render);
}
});
有人建议将模板制作成一个函数,以便在加载DOM后可以调用它,但我不确定这是否是最好的做法b/c我必须更改代码以“使Jasmine正常工作”,即使该功能在浏览器中也可以正常工作。我确实试过了(&loadFixtures
工作得很好),但在随后的测试中,我遇到了相同的问题——即
…需要在模板
的Handlebars编译过程开始之前——在规范开始在主干视图上运行之前,将HTML fixture附加到DOM
这是我的规格说明
describe('Items View', function() {
beforeEach(function() {
loadFixtures('index');
this.view = new ItemsView({
collection: items_scaffold // provided above
});
});
it("should have Handlebars template compiled", function() {
expect(this.view.template).toBeDefined();
});
});
我正在使用jasmine jquery.js
。在我的Rails布局HTML文件中,我将
放在正文的底部,所以我猜这不是一个“文档就绪”问题
我已经看过了一个类似问题的答案,但我似乎无法让它们在我的案例中起作用。是否有一个插件可以在jasmine规范开始运行之前(在beforeach
之前)将fixture附加到DOM,或者是jasmine jquery.js
中我错过的方法
非常感谢您在这方面提供的任何帮助。我相信这不是一个Jasmine问题,但实际上它与您编写视图的方式有关 问题在于,用于Handlebar编译的jQuery选择器是在声明时而不是实例化时进行评估的,这正是您所期望的:
var ItemsView = Backbone.View.extend({
template: Handlebars.compile($("[data-name=items]").html()),
...
在浏览器解析此代码声明时,您正在调用handlebar.comple
和jQuery选择器$(“[data name=items]”)
。这是在实例化之前的方式this.view=newitemsview({…})代码>
为了仅在执行new
时运行此操作,您需要将Handlebar编译步骤放在initialize方法中:
var ItemsView = Backbone.View.extend({
initialize: function() {
this.template = Handlebars.compile($("[data-name=items]").html()),
this.$el = $("#items");
this.listenTo(this.collection, "change", this.render);
},
render: function() {
this.$el.html(this.template({ items: this.collection.toJSON() }));
}
});
请尝试这种方式。如果您不想每次都解析jQuery选择器,我建议您甚至不要将模板存储在DOM中,而是存储在外部HBS文件中。然后您可以将其放回原来的位置。看起来这可能是中提到的Rails 4问题。在进行更改后,我仍然会收到错误,您通过了未定义的
。我有一茶匙茉莉2.0。中的一条评论说我需要更改jasmine.yml
中的src_文件,但看起来我甚至没有阅读jasmine.yml!我得研究一下这个。。。通读这个。我会投票给你,但还没有资格!关于外部HBS文件,我将如何访问ItemsView文件的外部HBS文件。谢谢很抱歉,我的建议不起作用。关于外部HBS文件,这取决于您如何执行整体模块策略。如果您使用RequireJS/AMD,您只需使用文本即可!插件。我相信Rails也有一种使用JST包含文件的方法,请看这里: