这是我的第一个问题。我正在学习Javascript,特别是Backbone.js,在this book的帮助下, Rapid Prototyping with JavaScript ,Azat Mardan。
在第4章中,介绍了Backbone.js框架,并通过教程和示例进行了解释。到目前为止,我没有直接关注本书代码的问题。但是,我一直在尝试复制示例代码,但它无法正常工作。但是,当我直接从github复制源代码时,它会莫名其妙地起作用。
这是我的代码。作者的代码可以在this link找到。
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script>
var appleData = [
{
name: "fuji",
url: "img/fuji.jpg"
},
{
name: "gala",
url: "img/gala.jpg"
}
];
var app;
var router = Backbone.Router.extend({
routes: {
'': 'home',
'apples/:appleName':'loadApple'
},
initialize: function(){
var apples = new Apples();
apples.reset(appleData);
this.homeView = new homeView({collection: apples});
this.appleView = new appleView({collection: apples});
},
home: function(){
this.homeView.render();
},
loadApple: function(appleName){
this.appleView.loadApple(appleName);
}
});
var homeView = Backbone.View.extend({
el: 'body',
template: _.template('Apple data: <%= data %>'),
render: function(){
this.$el.html(this.template({data: JSON.stringify(this.collection.models)}));
}
});
var Apples = Backbone.Collection.extend({
});
var appleView = Backbone.View.extend({
initialize: function() {
this.model = new (Backbone.Model.extend({}));
this.model.on('change', this.render, this);
this.on('spinner', this.showSpinner , this);
},
template: _.template('<figure>\
<img src="<%= attributes.url %>"/>\
<figcaption><%= attributes.name %></figcaption>\
</figure>'),
templateSpinner: '<img src="img/spinner.gif" width="30"/>',
loadApple: function(appleName){
this.trigger('spinner');
var view = this;
setTimeout(function(){
view.model.set(view.collection.where({name:appleName})[0].attributes);
},1000);
},
render: function(appleName) {
var appleHtml = this.template(this.model);
$('body').html(appleHtml);
},
showSpinner: function() {
$('body').html(this.templateSpinner);
}
});
$(document).ready(function(){
app = new router;
Backbone.history.start();
});
</script>
</head>
<body>
<div></div>
</body>
</html>
我尝试了DiffNow,但代码完全相同。
其他信息:
编辑:我已经解决了错误,好像我在这行中有一个奇怪的空白字符
showSpinner: function(){
之间的和{
感谢您的帮助!