【问题标题】:Backbone says undefined method method_name even if its defined骨干说未定义的方法method_name,即使它已定义
【发布时间】:2026-01-08 15:00:02
【问题描述】:

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

employee_collection 的 JavaScript

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

对于员工模型

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

对于员工视图

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 中定义了togleStatus() 方法,但它说它不是一个函数。我是不是在做一些破旧的事?

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

谢谢

【问题讨论】:

    标签: backbone.js undefined-function


    【解决方案1】:

    您需要告诉EmployeeCollection 要使用哪个模型子类,如下所示:

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

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

    【讨论】: