ccsakuweb
ccsakuweb

Reputation: 789

Extending Backbone Collections to add logic, with custom methods, is a bad practice?

Usually I find my self needing to write an object with a specific functionality that it is a set of models.

Finally I extend a collection and add more functions that works with its model.

I think is better show you an example:

My app has a set of permissions, related with the user and/or the version of the platform.

var Permissions = Backbone.Collection.extend({
   model: Permission,

   hasAccess: function (moduleCode) {
        ....
   },

   allowAccess: function (moduleCode) {
        ....
   },

   ...

With that methods I change the format of a property of a permission (the model). (My permissions are a concatenation of code with an string that identify the type of permission.)

A workmate tells me that it is wrong. In .NET he creates a class and he adds a private list and makes the changes to it. He does not inherit the list and changes it.

He would make a model and inside it he would add a collection property

this.set("permissionsCollection", new Backbone.Collection.extend({model: Permission}))

[Comment: I don't understand why he creates properties of everything, I think in his case it is not needed.] -> But this is another question

I think in a different way. I know the Collection has internally that list. I have a great potencial in Backbone.Collections, why do I have to use a model that it is not necessary? If I don't need that encapsulation... I think that it is not necessary, he is overprogramming in my opinnion.

Am I wrong? Did I not know how to use BackboneJS Collections?

Thank you in advance.

Upvotes: 1

Views: 2094

Answers (1)

Akos K
Akos K

Reputation: 7133

At the beginning I had something called helper with similar methods:

        findAttr: function (model, name) {
            var attrs = model.get('app_attrs');
            if (attrs !== undefined) {
                return this.findByAttrName(attrs, name);
            }
        },
        findByAttrName: function (array, name) {
            return _.find(array, function(a) {
                if (a.attrName === name) {
                    return a;
                }
            });
        }

The view code was more awkward:

        render: function () {
            var attr = helper.findAttr(this.model, 'user');
            ...
            return this;
        }

The only logical solution was to move these methods into the model (this.model in the above case). After refactoring I've got:

        render: function () {
            var attr = this.model.findAttr('user');
            ...
            return this;
        }

which is of course more readable than the previous solution.

Upvotes: 1

Related Questions