我开始学习Backbone JS,我收到此错误:Uncaught TypeError: Cannot read property 'id' of undefined
这是我的代码:
var User = Backbone.Model.extend({
urlRoot: 'api/users',
defaults:{
firstName: '',
lastName: '',
age: 0
}
});
var UsersList = Backbone.Collection.extend({
model: User,
url: 'api/users'
});
var usersList = new UsersList();
var UserView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#user-template').html()),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var UserListView = Backbone.View.extend({
el: '.page',
template: _.template($('#user-list-template').html()),
initialize: function(){
this.listenTo(usersList,'reset',this.addAll);
},
render: function(options){
if(options.id){
var user = new User({id: options.id});
user.destroy();
router.navigate('',{trigger:true});
}
usersList.fetch({reset: true});
this.$el.html(this.template());
},
addAll: function(){
usersList.forEach(this.addOne,this);
},
addOne: function(user){
var userView = new UserView({model: user})
$('.users-list').append(userView.render().el)
}
});
var userListView = new UserListView();
var Router = Backbone.Router.extend({
routes: {
'' : 'home',
'new' : 'add-user',
'edit/:id' : 'edit-user',
'delete/:id' : 'delete-user',
}
});
var router = new Router();
router.on('route:home',function(){
userListView.render();
});
router.on('route:add-user',function(){
addUserView.render();
});
router.on('route:edit-user',function(id){
editUserView.render({id:id});
});
router.on('route:delete-user',function(id){
userListView.render({id:id});
});
Backbone.history.start();
它在这一行显示我的错误:if(options.id){
我不明白为什么会出现这个错误。实际上我正在尝试从列表中删除用户。
已更新:(我也有以下视图,但if(options.id)
没有显示错误),那么为什么id
显示错误为UserListView
未定义? IT真的让我感到惊讶。为一个视图工作,但显示另一个视图的错误。
var EditUserView = Backbone.View.extend({
el: '.page',
template: _.template($('#edit-user-template').html()),
render: function(options){
if(options.id){
var user = new User({id: options.id})
var that = this;
user.fetch({
success: function(user){
that.$el.html(that.template({user: user}));
}
});
}
},
events: {
'submit .update-user-form' : 'updateUserForm'
},
updateUserForm: function(e){
e.preventDefault();
var userDetails = {firstName: $('#firstname').val(), lastName: $('#lastname').val(), age: $('#age').val()};
var user = new User({id: $('#id').val()});
user.save(userDetails,{
success: function(){
router.navigate('',{trigger: true});
}
});
}
});
var editUserView = new EditUserView();