视图中的 el 在测试中未定义 backbone

el in view is undefined in testing backbone

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

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

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

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

最简单的解决方案是将 jQuery 的东西留给 Backbone 并只使用 el:

的选择器
el: '#container'

然后Backbone会在需要构建$el的时候参考DOM,到时候你应该有#container了。