我有一个employee_collection,employee_model,employee_collection_view和employee_view,如下所示。
Javascript for employee_collection
var EmployeeCollection = Backbone.Collection.extend({
url: "/employees"
})
对于employee_model
var Employee = Backbone.Model.extend({
toogleStatus: function(){
if(this.get('fired') === true){
this.set({fired: false});
}else{
this.set({fired: true});
}
this.save();
}
});
对于employee_collection_view
var EmployeeListView = Backbone.View.extend({
tagName: 'table',
className: "table table-striped",
initialize: function(options){
this.display_type = options.display_type
},
render: function(){
this.collection.models.forEach(this.addOne, this);
},
addOne: function(employee){
console.log(this.display_type);
var employeeView = new EmployeeView({model: employee});
employeeView.render();
this.$el.append(employeeView.el);
}
});
对于employee_view
var EmployeeView = Backbone.View.extend({
tagName: "tr",
template: _.template("<td><%= first_name %></td><td><%= last_name %> </td><td> <%= address %></td><td> <%= phone %></td><td><%= fired %></td><td><input type='button' value=<% (fired === true) ? print('hire') : print('fire') %> /></td>"),
initialize: function(){
this.model.on('change', this.render, this);
},
events: {
'click input[type="button"]': 'toogleStatus'
},
toogleStatus: function(){
console.log(this.model);
this.model.toogleStatus();
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
console.log(this.$el.html());
},
setupView: function(){
console.log($("#employees_list").html());
}
});
页面加载后,我可以在主页中看到员工列表,并且在最后一列有一个按钮,如果触发属性为true,则触发,如果触发状态为false则为fire。
但最让我烦恼的是,当我按下按钮(开火/租用)时,来自employee_view的toogleStatus会被触发,但错误会在
突然显示this.model.toogleStatus();
说
TypeError: this.model.toogleStatus is not a function
this.model.toogleStatus();
我记录了this.model,并将其打印出来。
尽管我在employee_model中定义了toogleStatus()方法,但它说它不是一个函数。我做了什么事吗?
application.js具有以下代码。
$(function(){
var router = new Router();
router.on('route:home', function(){
var employeeCollection = new EmployeeCollection();
employeeCollection.fetch({
success: function(employees){
var employeeListView = new EmployeeListView({collection: employees, display_type: "grid"});
employeeListView.render("table");
$('.page').html(employeeListView.el);
}
});
});
Backbone.history.start();
});
由于
答案 0 :(得分:2)
您需要告诉EmployeeCollection
使用哪个模型子类:
var EmployeeCollection = Backbone.Collection.extend({
url: "/employees",
model: Employee
})
默认情况下,集合将实例化基本的Backbone.Model
父类,因此不会有任何Employee
子类的自定义方法。