0

我有一个employee_collection、employee_model、employee_collection_view 和employee_view,如下所示。

employee_collection 的 Javascript

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());
  }
});

页面加载后,我可以在主页中看到员工列表,最后一列有一个按钮,如果解雇属性为真,则雇用,如果解雇状态为假,则解雇。

但是让我烦恼的是,当我按下按钮(解雇/雇用)时,employee_view 的工具状态被触发但错误弹出

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();
});

谢谢

4

1 回答 1

2

您需要EmployeeCollection像这样告诉要使用哪个模型子类:

var EmployeeCollection = Backbone.Collection.extend({
  url: "/employees",
  model: Employee
})

默认情况下,集合将实例化基本Backbone.Model父类,因此不会有任何子Employee类的自定义方法。

于 2013-02-11T05:01:04.070 回答