我想显示一个列表,一旦单击列表中的某个项目,我希望隐藏该列表,并检索并显示该项目的详细信息。
鼠标单击触发,从 REST Web 服务检索详细信息,并隐藏项目列表。问题是在我刷新页面之前不会出现项目详细信息。我不太明白我做错了什么。
这是我的代码示例:
<html>
<head>
<title>Backbone Test</title>
<script type="text/javascript" src="js/lib/jquery-1.7.1-min.js"></script>
<script type="text/javascript" src="js/lib/underscore-min.js"></script>
<script type="text/javascript" src="js/lib/backbone-min.js"></script>
</head>
<body>
<div>VIN Search List:</div>
<div id="item-list" />
<div id="item-details" />
<script type="text/javascript">
$(function()
{
var Item = Backbone.Model.extend({
urlRoot: "rest/search",
defaults: {
"uid": ""
}
});
var Items = Backbone.Collection.extend({
model: Item,
url: "rest/search/",
});
var ItemDetail = Backbone.Model.extend({
urlRoot: "rest/search/details",
defaults: {
"uid": "",
"details": ""
},
url : function() {
return this.id ? this.urlRoot + '/' + this.id : this.urlRoot;
}
});
var ListView = Backbone.View.extend(
{
tagName: "ol",
initialize: function()
{
_.bindAll(this, 'render');
this.model.bind("destroy", this.close, this);
},
render: function()
{
_.each(this.model.models, function(uid) {
$(this.el).append( new ItemView({model:uid}).render().el );
}, this);
return this;
},
close: function()
{
$(this.el).unbind();
$(this.el).remove();
},
});
var ItemView = Backbone.View.extend(
{
tagName: "li",
template: _.template("<%= uid %>"),
events: { "click": "showDetails" },
initialize: function()
{
_.bindAll(this, 'render');
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render: function(eventName)
{
$(this.el).html( this.template( this.model.toJSON() ) );
return this;
},
close: function()
{
$(this.el).unbind();
$(this.el).remove();
},
showDetails: function()
{
app.navigate("details/" + this.model.get("uid"), {trigger: true});
return false;
},
});
var DetailsView = Backbone.View.extend(
{
tagName: "ul",
template: _.template("<li><%= uid %></li><li><%= details %></li>"),
initialize: function()
{
_.bindAll(this, 'render');
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render: function(eventName)
{
$(this.el).html( this.template( this.model.toJSON() ) );
return this;
},
close: function()
{
$(this.el).unbind();
$(this.el).remove();
},
});
var AppRouter = Backbone.Router.extend({
routes:
{
"": "list",
"details/:uid": "Details"
},
list: function()
{
var self = this;
this.itemList = new Items();
this.itemList.fetch(
{
success: function()
{
self.listView = new ListView({model: self.itemList});
$('#item-list').html( self.listView.render().el );
}
});
},
Details: function(uid)
{
if (this.lListView) this.listView.close();
var self = this;
this.details = new ItemDetail({id: uid});
this.details.fetch(
{
success: function()
{
self.detailsView = new DetailsView({model: self.details});
$('#item-details').html( self.detailsView.render().el );
}
});
},
});
// Start up
var app = new AppRouter();
Backbone.history.start();
});
</script>