从服务器获取模型

Fetching models from the server

我有一个使用 Node.js 编写的 RESTful 服务。如果我在浏览器中打开 http://localhost:5000/links,我将获得链接集合:

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

我需要从 backbone 应用程序中获取此集合:

(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);           

})();

这是一个控制台:

我可以在控制台右侧看到我的对象 (c3.attributes)。但是为什么集合的长度为零呢?我怎样才能得到这个对象?

经典backbone问题。

试试这个:

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

编辑:此外,我认为集合 return 是一个承诺,因此替代解决方案可能是:

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

我自己没有使用过它,但我认为它应该有用。希望对你有帮助。