子视图事件回调是否优先?

Does the child View event callback takes precedence?

我有一些相关的 backbone 浏览量:

第一个:

App.Views.TreeGrowthBase = App.Views.TreeGrowthBase.extend({
  events: {
    'submit form': 'submitForm',
...

然后在同一个文件中:

submitForm: function(e) {
    e.preventDefault();

以及应用中的其他地方:

App.Views.WineTreeGrowthBase = App.Views.TreeGrowthBase.extend({
  submitForm(event) {
    event.preventDefault();

我的问题:在最后一段代码中...语法是什么:

submitForm(event) {
    event.preventDefault();

这是方法调用吗?定义方法?冒号在哪里?

哪个优先?我想象子视图的 submitForm 方法定义发生了......如果它是一个方法定义?

Method definition shorthand

submitForm(event) {
    event.preventDefault();

这是 ES6 (ECMAScript 2015) 中新增的方法定义 shorthand。

相当于

submitForm: function submitForm(event) {
    event.preventDefault();

The shorthand syntax uses named function instead of anonymous functions (as in foo: function() {}). Named functions can be called from the function body (this is impossible for anonymous function as there is no identifier to refer to). For more details, see function.

并在具有可用新功能的浏览器中工作(如 IE 以外的浏览器)。

覆盖函数

在 Backbone class(extend 函数的结果)的子函数中重写的任何方法都优先于父函数。如果你想调用父函数,还是可以的:

submitForm: function(event) {
    // Using the Backbone '__super__'
    ThisClass.__super__.submitForm.apply(this, arguments);
    // Or the JavaScript preferred way
    ParentClass.prototype.submitForm.apply(this, arguments);
    event.preventDefault();
}

这不是 Backbone 特有的。这是原型链的正常行为。 Backbone 只是将复杂性包装在一个简单的 extend function.

查看此 in-depth answer 了解更多信息。


不要使用 this.constructor.__super__ 因为它不能保证是实际的 class 并且它可能是子 class 的构造函数,导致 调用堆栈溢出。赞成 MyCurrentClass.__super__,它是明确的,并为潜在的扩展问题关上了大门。