backbone.js/underscore.js错误:没有方法'html'

use*_*715 4 javascript ruby-on-rails backbone.js

当我尝试导入一个看起来像这样的模板时,我似乎遇到了使用backbone.js/underscore.js的砖墙:

<script type="text/template" id="overview_template">
<div>
  Sample text
</div>
</script>
Run Code Online (Sandbox Code Playgroud)

错误如下:

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
Run Code Online (Sandbox Code Playgroud)

触发错误的代码this.el.html(template);如下:

 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(); 
Run Code Online (Sandbox Code Playgroud)

我不确定是什么导致了这一点,但它一直让我疯狂.

Dmi*_*sev 7

.html()方法是jQuery对象的方法.当你使用this.el时 - 它是一个DOM对象.让jQuery对象使用这个.$ el(它由backbone.js jQuery对象缓存)或$(this.el).

所以,你的代码应该是这样的:

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

要么

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