El in sight of undefined when testing framework

I would like to validate my view based on the base view. but i have a problem, i am trying to get an element of my view using this.$el

, the result is empty. when i check this.el

, the result isundefined

when i try to search with $('#container')

it exists and when i run it it works as well. Tag exists, here is my view code

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;
});

      

and here is my test code:

    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;
      });
    });
  });
});

      

Do you understand why this is happening? I even try to add $(document).ready(function(){})

. thank

+3


source to share


1 answer


Keep in mind that $('#container')

this is a function call, so your code is equivalent to this:

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

      

This means your code will look for #container

when yours is executed Backbone.View.extend

. There appears to be no element #container

when this happens, so you get the value undefined

for el

when Backbone tries to execute the un-jQuery-ify el

you provided.



The simplest solution is to leave the jQuery Backbone stuff and just use a selector for el

:

el: '#container'

      

Then Backbone will access the DOM when it needs to be built $el

, which is when you should have #container

.

+3


source







All Articles