我想从backbone视图中测试我的视图,但遇到了问题,我试图使用this.$el
获取我的视图元素,结果为空。当我检查this.el
时,结果为undefined
当我尝试使用$('#container')
搜索它时,它是存在的,并且当我运行它时,它也有效。标签是存在的,
这是我的视图代码
define([
'jquery',
'underscore',
'backbone',
'text!templates/setting.html',
'js/service/Config'
],function($, _, Backbone, settingTemplate, Config){
var settingView = Backbone.View.extend({
el: $("#container"),
initialize: function(){
_.bindAll(this, "render");
},
render: function(){
data = {}
var compiledTemplate = _.template(settingTemplate, data);
this.$el.append(compiledTemplate);
this.delegateEvents();
DroneConfig.getAll(function(obj){
$('input[name=url]').val(obj.url);
$('input[name=repo]').val(obj.repo);
$('input[name=hostname]').val(obj.hostname);
$('textarea[name=api_key]').val(obj.api_key);
});
}
});
return settingView;
});
以下是我的测试代码:
define(['js/view/settingView','text!templates/setting.html'], function(SettingView, texts){
describe("Setting View", function() {
it('render successfully', function() {
$('body').append(__html__['app/js/test/test.html']);
$(document).ready(function(){
var x = new SettingView();
x.render();
expect($('#setting').html()).to.not.be.empty;
});
});
});
});
你有没有想过为什么会发生这种情况?我甚至尝试添加$(document).ready(function(){})
。谢谢。
new SettingView("<div></div>")
,并且该div将成为你的el
。 - Jed Schneider