1

I have a RESTful service which have being written using Node.js. If I open http://localhost:5000/links in the browser I will get the collection of links:

[{"_id":"5597f5d3e9a768531c07468a","uri":"http://google.com","title":"google","__v":0,"tags":["one","two"]}]

I need to get this collection from backbone application:

(function () {

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

    var LinkCollection = Backbone.Collection.extend({
        model: Link,
        url: 'http://localhost:5000/links'
    });

    var links = new LinkCollection();
    links.fetch();
    console.log(links);
    console.log(links.length);           

})();

Here is a console:

enter image description here

I can see my object the right side of the console (c3.attributes). But why the length of collection is zero? And how can I get this object?

Dominic
  • 62,658
  • 20
  • 139
  • 163
ceth
  • 44,198
  • 62
  • 180
  • 289
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – ivarni Jul 06 '15 at 15:13

1 Answers1

2

Classic backbone issue.

Try this:

links.fetch({
    success:function(response) {
        //here are your results
    }
});

Edit: Also I think a collection return a promise so an alternative solution could be:

links.fetch().then(function(response) {
});

haven't use it myself but I think it should work. Hope it helps.

François Richard
  • 6,817
  • 10
  • 43
  • 78
  • 1
    It's a jQuery promise so instead of `then` it would be `done` – Dominic Jul 06 '15 at 15:24
  • Thanks. As I see I can get my object as `console.log(links.models[0].attributes);` in this function. It is right way or there is a better solution? – ceth Jul 06 '15 at 15:32
  • ok I understand, check this on the callback function(model, response) {} you'll get your models easily I think – François Richard Jul 06 '15 at 15:51
  • 1
    @demas you would use the `links.each` to iterate over them, and `links.at(0)` instead of `links.models[0]` but they essentially do the same thing (and there is also `links.get` to retrieve models via a model object or id instead of index) – Dominic Jul 06 '15 at 17:23