当我点击页面上的链接时,浏览器中的网址会发生变化,但视图无法更改。当我刷新页面时,视图渲染就好了。
我的itemView.js是这样的:
var ItemView = Backbone.View.extend({
tagName: 'tr',
className: 'single-item',
template: _.template('<td><%= name %></td><td><%= phoneNumber %></td><td><a href="/#people/<%= id %>"class="details">Click for details</a></td>'),
render: function(){
this.$el.html(this.template(this.model.attributes));
this.$el.attr('data-itemid', this.model.id);
return this.$el;
}
});
router.js
var UserRouter = Backbone.Router.extend({
initialize: function () {
this.mainView = new MainView();
this.listView = new ListView();
$('.wrap').append(this.mainView.render());
},
routes: {
"people/:id": "showPerson"
},
loadView: function(view){
if( this.view ){
this.view.remove();
};
this.view = view;
this.mainView.$el.html(this.view.render());
},
showPerson: function(id){
var self = this;
this.listView.collection.on('sync', function () {
var myModel = this.get(id);
self.loadView(new SingleView({model: myModel}));
});
}
});
在main.js
var router = new UserRouter;
Backbone.history.start();
如您所见,我使用路由器作为应用入口点。我只是不明白 - 我是否必须处理链接点击或路由器应该这样做?
生成的链接如下所示:
<a href="/#people/5" class="details">Click for details</a>