Seba Kerckhof
Seba Kerckhof

Reputation: 1391

requirejs: New object of same type as module

I have a backbone application using requirejs and I need to filter a collection by model attribute.

Therefore I want to return a new collection with the filtered items.

However, this is my collection (collections/ActorList.js) and inside it, I want to instantiate a new ActorList. I tried the code below, but this doesn't seem to work (ActorList seems to be undefined...)

collections/ActorList.js:

define([
    'backbone',
    'models/Actor',
    'collections/ActorList'
], function (Backbone, Actor, ActorList) {
    'use strict';

    return Backbone.Collection.extend({
        model: Clothe,
        url : "assets/data/clothes.json",

        filterBy: function(attribute, value) {
            var filtered = this.filter(function(model) { return model.get(attribute) === value; });
            return new ActorList(filtered);
        }
    });
});

Upvotes: 0

Views: 124

Answers (1)

Louis
Louis

Reputation: 151380

You question shows that collections/ActorList.js requires itself. That's a circular dependency.

How about doing this?

define([
    'backbone',
    'models/Actor',
], function (Backbone, Actor) {
    'use strict';

    var ActorList = Backbone.Collection.extend({
        model: Clothe,
        url : "assets/data/clothes.json",

        filterBy: function(attribute, value) {
            var filtered = this.filter(function(model) { return model.get(attribute) === value; });
            return new ActorList(filtered);
        }
    });

    return ActorList;
});

Upvotes: 1

Related Questions