Search code examples
javascriptbackbone.jsecmascript-6

Does the child View event callback takes precedence?


I have a few related backbone Views:

First:

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

and then in the same file:

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

and elsewhere in the app:

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

My questions: In that last piece of code... what is the syntax:

submitForm(event) {
    event.preventDefault();

Is that a method call? Defining a method? Where are the colons?

Which one takes precedence? I imagine the child view's submitForm method definition takes place... if it is a method definition?


Solution

  • Method definition shorthand

    submitForm(event) {
        event.preventDefault();
    

    This is the method definition shorthand new in ES6 (ECMAScript 2015).

    It's equivalent to

    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.

    and works in browser which have the new features available (like other than IE).

    Overriding functions

    Any method overridden in a child of a Backbone class (the result of the extend function) takes precedence on the parent function. If you would like to call the parent function, it's still possible:

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

    This is not specific to Backbone. It's the normal behavior of the prototype chain. Backbone just wraps the complexity in a simple extend function.

    See this in-depth answer for more info.


    Do not use this.constructor.__super__ because it's not guarantied to be the actual class and it could be the constructor of the child class, causing a call stack overflow. Favor MyCurrentClass.__super__, it's explicit and close the door to potential extending problems.