【发布时间】:2014-07-31 05:48:46
【问题描述】:
我是骨干新手,正在尝试制作图书图书馆应用程序。运行此代码时,它不显示模板。
这是我的 index.html
<html>
<head>
<title>Example</title>
</head>
<body>
<form>
Name:<input type='text' id='name'/><br>
Author:<input type='text' id='auth'/><br>
Keyword:<input type='text' id='keyword'/><br><br>
<button id="add">Add</button>
</form>
<div id='book_list'>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.io/backbone/backbone-min.js"></script>
<script src="script.js"></script>
<script id="bookTemplate" type="text/template">
<ul>
<li><%= name %></li>
<li><%= auth %></li>
<li><%= keyword %></li>
</ul>
<button class="delete">Delete</button>
</script>
</body>
</html>
这是 script.js
$(function(){
var bookmodel = Backbone.Model.extend({
defaults: {
name:'temp',
auth:'meee',
keyword:'nonee'
},
});
var booklist = Backbone.Collection.extend({
model:bookmodel
});
var bookview= Backbone.View.extend({
tagName:'div',
className: 'bookContainer',
template: _.template( $('#bookTemplate').html()),
events:{
'click .delete':'deleteBook'
},
render : function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
deleteBook: function(){
this.model.destroy();
this.remove();
}
});
var library = Backbone.View.extend({
model: bookmodel,
initialize: function( initialBooks ) {
$el='#book_list';
var one=new bookmodel({name:'ankur 1',auth:'asdf 1',keyword:'asdfkasdf 1'});
var two=new bookmodel({name:'ankur 2',auth:'asdf 2',keyword:'asdfkasdf 2'});
var bookcoll= [one,two];
this.collection = new booklist(bookcoll);
this.render();
},
render:function(){
this.collection.each(function (item){
var k= new bookview({model:item});
this.$el.append(k.render().el);
},this);
},
});
var xyz= new library();
})
另外,当我尝试这样编写代码时:
var library = Backbone.View.extend({
model: bookmodel,
$el:'#book_list';
..... //rest of the code
)};
var xyz= new library();
然后,它导致:Uncaught TypeError: undefined is not a function, at linevar xyz= new library();
【问题讨论】:
-
在你的库声明中,分号应该是
#book_list之后的逗号 -
在你的
initialize函数中你有$el:"#book_list";应该类似于this.el = "#book_list"; -
是的,有一个逗号,我在这里放错了,
-
还是一样的场景.. 模板不渲染。
-
好的thanx..我在等..
标签: javascript jquery html backbone.js jsfiddle