Define a public method in a backbone model-Collection of common programming errors

I need to iterate over a backbone collection and get an array of objects that are derived from the models within the collection.

The problem is that I do not know how to let the collection access a method defined when creating the model definition inside the object given in: Backbone.Model.extend({})

This is an example of the architecture that I have so far:

// THE MODEL
var TheModel = Backbone.Model.extend({
    // THE FOLLOWING IS NOT AVAILABLE AS A METHOD OF THE MODEL:
    //     This isn't the actual method, but I though it might be helpful to
    //     to demonstrate that kind of thing the method needs to do (manipulate:
    //     map data and make it available to an external library)
    get_derived_object: function(){
        return this.get('lat') + '_' this.get('lon');
    }

});

// THE COLLECTION:
var TheCollection = Backbone.Collection.extend({
    // Use the underscore library to iterate through the list of
    //     models in the collection and get a list the objects returned from
    //     the "get_derived_object()" method of each model:
    get_list_of_derived_model_data: function(){
        return _.map(
            this.models,
            function(theModel){
                // This method is undefined here, but this is where I would expect
                //     it to be:
                return theModel.get_derived_object();

            }
        );
    }

});

I’m not sure where I am going wrong here, but I have a few guesses: * The collection is not iterating over it’s models in the way that it should * Public methods cannot be defined in Backbone.Model.extend({}) * I am looking in the wrong place for the public methods * Some other architectural mistake derived from a misunderstanding of how Backbone.js is intended to be used

Any help is appreciated, thanks so much!

Edit

The problem was that there was actually a bug in this code. When the collection was populated, it did not have a reference to “TheModel” as its model type, so it created its own models.

This line of code needed to be added when the collection was defined: model: TheModel

var theCollection = Backbone.Collection.extend({
    model: TheModel,
    ...
});
  1. Instead of using:

    return _.map(
        this.models,
        function(theModel){
            // This method is undefined here, but this is where I would expect
            //     it to be:
            return theModel.get_derived_object();
         }
    );
    

    Why not use the built-in collection version:

    return this.map(function(theModel){
        return theModel.get_derived_object();
    });
    

    Not sure if that will help, but it’s worth a shot.

    And for the record, all methods defined in the first argument to new Backbone.Model( are “public”, so you’ve got the basics right.

Originally posted 2013-11-09 23:22:06.