Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js / underscore.js error: has no method 'html'

I seem to be running into a brick wall with backbone.js / underscore.js when I try to import a template that looks like:

<script type="text/template" id="overview_template">
<div>
  Sample text
</div>
</script>

The error reads:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'html' navigation.js:356 
Backbone.View.extend.render navigation.js:356 
Backbone.View.extend.initialize navigation.js:351 
g.View backbone-min.js:33 d backbone-min.js:38 
(anonymous function) navigation.js:379 
f.Callbacks.n jquery-1.7.1.min.js:2 
f.Callbacks.o.fireWith jquery-1.7.1.min.js:2 
e.extend.ready jquery-1.7.1.min.js:2 c.addEventListener.B

The code that triggers the error is this.el.html(template); in the following:

 var OverviewView = Backbone.View.extend({
  el: $('#overview_container'),

  initialize: function() {
       this.render();
  },

  render: function() {
    var template = _.template( $("#overview_template").html(), {} );
    this.el.html(template);
  },

  defaults: {
    tip_of_the_day: 'open',
    news: 'open',
    recent_presentations: 'open'
  },

  events: {
    "click .overview_subsection_header": "toggleSubsection"     
  },

  toggleSubsection: function (event) {
    $(this).parent().find('.overview_subsection_content').toggle();
  }
 });

 var overview_view = new OverviewView(); 

I'm not sure what is causing this but it's been driving me insane.

like image 434
user895715 Avatar asked Dec 12 '22 01:12

user895715


1 Answers

.html() method is the method of jQuery object. When you use this.el - it's a DOM object. to get jQuery object use this.$el (it's cached by backbone.js jQuery object) or $(this.el).

So, your code should look like this:

  render: function() {
    var template = _.template( $("#overview_template").html(), {} );
    this.$el.html(template);    
  }

or

  render: function() {
    var template = _.template( $("#overview_template").html(), {} );
    $(this.el).html(template);    
  }
like image 87
Dmitry Belaventsev Avatar answered Dec 20 '22 09:12

Dmitry Belaventsev