Error backbone.js / underscore.js: does not have a 'html' method

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

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

Error:

 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 causing 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 causes this, but it drove me crazy.

+4
source share
4 answers

The .html () method is a jQuery object method. When you use this.el is a DOM object. to get jQuery object use this. $ el (it is cached by the 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); } 
+7
source

must not be

this.$el.html(template);

T. jQuery wrapped el.

+4
source

You are trying to connect a view to an existing element, #overview_container . But, of course, the view class is created before the browser initializes the DOM.

Since your template is stored in #overview_container , presumably you do not want the view to appear in this element? Try removing the el property in the view and attaching the views element wherever you want it on the page.

Also, this is an agreement with Backbone to return this from the render method, so that you can easily and easily create and attach an element, for example:

 $(document.body).append((new OverviewView()).render().el); 

You can render in the initializer if you want, but this is not standard practice.

+2
source

try

 this.$el.html(template) 

instead

 this.el.html(template) 
0
source

Source: https://habr.com/ru/post/1414503/


All Articles