M老立
M老立

Reputation: 347

How to call methods inside of a Backbone Collection

I'm new to Backbone.js, well even new to Javascript, not sure how to put my question in phrase, I want a function to be called and returns result as an attribute in the same collection.

var EnrollmentCollection = Backbone.Collection.extend({

    url: "/some/prefix" + this.getPath() + "/some/suffix",

    getPath: function() {
        var result;

        $.ajax({
            type: 'GET',
            url: '/this/is/a/url',
            async: false,
            dataType: 'json',
            success: function(data) {
                result = data[0].someattribute;
            }
        });

        return result;
    }
});

As you can see, getPath() method should be returning a value as value of url, however, browser gives following error:

Uncaught TypeError: Cannot read property 'getPath' of undefined(anonymous function)

Any help is appreciated.

Upvotes: 1

Views: 320

Answers (3)

som
som

Reputation: 2477

Adding to @MindTastic's answer above, and with the revelation of async: false (to create a blocking ajax call), i would consider simply moving your getPath method onto url:

var EnrollmentCollection = Backbone.Collection.extend({

    // doesn't need to be wrapped as 'url' accepts functions
    url: function () {
        var result;

        $.ajax({
            type: 'GET',
            url: '/this/is/a/url',
            async: false,
            dataType: 'json',
            success: function(data) {
                result = data[0].someattribute;
            }
        });

        return result;
    }
});

See the Backbone Docs - Collection URLs for more info

Upvotes: 1

Kenzo-kun
Kenzo-kun

Reputation: 156

Add initialize method for your collection, and add _.bindAll(this) like this:

initialize: function() {
    _.bindAll(this);        
}

After adding the code above, you can now call your method like this:

url: this.getPath();

Upvotes: 1

Mindastic
Mindastic

Reputation: 4131

With the code you are using:

url: this.getPath(),

You are executing the function this.getPath() and it doesn't exist yet because it is defined below.

Try doing

url: (function(){
  var result;

        $.ajax({
            type: 'GET',
            url: '/this/is/a/url',
            async: false,
            dataType: 'json',
            success: function(data) {
                result = data[0].someattribute;
            }
        });

        return result;
}())

Upvotes: 2

Related Questions