vania-pooh
vania-pooh

Reputation: 2977

Backbone: properties in ECMAScript 6

I'm searching for a good ECMAScript 6 equivalent of the following Backbone code:

var MyModel = Backbone.Model.extend({});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

This pattern is widely used in Backbone models, views and collections. Can I do better than the code below (e.g. by creating a method named "model")?

export class MyModel extends Backbone.Model {}

export class MyCollection extends Backbone.Collection {
    constructor() {
        super({model: MyModel});
    }
}

Upvotes: 4

Views: 258

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161557

I'd use a getter:

export class MyModel extends Backbone.Model {}

export class MyCollection extends Backbone.Collection {
  get model() {
    return MyModel;
  }
}

Upvotes: 3

Akos K
Akos K

Reputation: 7133

Of course, just don't use the class keyword:

var MyModel = Backbone.Model.extend({});

var MyCollection = Backbone.Collection.extend({
    model: MyModel
});

This code is actually more reusable than the ECMAScript 6 equivalent you wrote. The ECMAScript 6 is actually worse than the original one.

You have to understand that in JavaScript objects can exist without classes and that feature is extremely important.

Here is what Douglas Crockford wrote on prototypal inheritance back in 2008: http://javascript.crockford.com/prototypal.html

Upvotes: 0

Related Questions