2013-01-25 22 views
1

尝试通过使用Backbone.js通过模板从视图中输出一些值,但列表项不显示在网页上,请看看并告知缺少的内容。谢谢_.template不工作 - backbone.js

<script type="text/template" id="myid"> 
    <li> <%= value %> </li> 
</script> 
<script type="text/javascript"> 
(function($){ 
    ListView = Backbone.View.extend({ 
     tagName:'ul', 
     initialize:function(){ 
      this.template = _.template($('#myid').html()); 
     }, 
     render:function(){ 
     this.$el.append(this.template({value:"Joe Blogg"})); 
     return this;  
     } 
    }); 
    $(document).ready(function(e) { 
     myListView = new ListView(); 
    }); 
    })(jQuery); 
+0

这不工作的唯一原因是你没有调用'render()'。其他一切都很好。 –

回答

4

请试试这个。

(function($){ 
    var ListView = Backbone.View.extend({ 
     tagName:'ul', 
     $el: $(this.tagName), 
     initialize:function(){ 
      this.template = _.template($('#myid').html()); 
     }, 
     render:function(){ 
      this.$el.append(this.template({value:"Joe Blogg"})); 
      $('body').append(this.$el); 
     } 
    }); 
    $(document).ready(function(e) { 
     var myListView = new ListView(); // call initialize() 
     myListView.render(); // call render() 
    }); 
})(jQuery); 

我使用jQuery.js和Underscore.js和Backbone.js。

并始终使用“var”。

+0

感谢Gecko :) $ el:$(this.tagName)对我很有帮助 – user1336103

+0

您不需要执行'$ el:$(this.tagName);',那只是做了更多的工作而已,必要。如果声明了'tagName','tagName'自动变成'el'。调用'this.render();'修复了实际问题。 –

0

你需要调用render,然后实际添加你的观点的el到页面的某个地方。

$(document).ready(function(e) { 
    var myListView = new ListView(); 
    $("body").append(myListView.render().el); 
}); 
0

试试这个

this.$el.empty(); 
    this.$el.html(this.template(this.model.attributes)); 

在你DOM准备事件调用.render()方法

$(document).ready(function(e) { 
    myListView = new ListView(); 
    myListView.render(); 
}); 
+0

感谢Sushanth :) – user1336103

相关问题