gpt4 book ai didi

javascript - el in view 在测试 backbone 中未定义

转载 作者:行者123 更新时间:2023-11-29 10:40:29 24 4
gpt4 key购买 nike

我想从主干 View 测试我的 View 。但是我遇到了问题,我尝试使用 this.$el 获取 View 的元素,结果是空的。当我检查 this.el 结果是 undefined

当我尝试使用 $('#container') 搜索它时,它是存在的,当我运行它时,它也有效。标签存在,这是我的 View 代码

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(){})。谢谢

最佳答案

请记住,$('#container') 是一个函数调用,因此您的代码等同于:

var $el = $('#container');
var settingView = Backbone.View.extend({
el: $el,
//...
});

这意味着当执行 Backbone.View.extend 时,您的代码将寻找 #container。显然,发生这种情况时没有 #container 元素,因此当 Backbone 尝试取消 jQuery-ify 时,您最终得到 elundefined 值您提供的 el

最简单的解决方案是将 jQuery 的东西留给 Backbone,只为 el 使用一个选择器:

el: '#container'

然后 Backbone 将在需要构建时查询 DOM $el那时你应该有一个 #container

关于javascript - el in view 在测试 backbone 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com