使用骨干j中的相同集合从不同URL获取数据

Sud*_*udo 4 javascript jquery backbone.js backbone.js-collections backbone-model

我有必须调用4的外部API如集合:http://www.abc.com,http://www.fgt.com,http://www.jkl.comHTTP://www.rty .com.

我有一个名为Todos.js的Collection.有没有办法可以在一个集合中一起获取4个api,因为所有四个api都会为我提供相同的模型响应所以我从4 apis得到的响应具有相同的数据结构,即"name"和"link".

有没有办法可以在同一个集合中附加所有回复?实现这一目标的最佳方法是什么?

McG*_*gle 6

我认为方法是覆盖fetch,在那里你对每个API进行Ajax调用.将返回的部分集存储在临时数组中,当完成所有4个部分集时,使用创建集合this.reset.(您可以使用JQuery Deferred,或者只保留已返回的调用次数的内部计数.)

像这样的东西:

var Collection = Backbone.Collection.extend({

    fetch: function() {
        this.completeCount = 0;
        this.errorCount = 0;
        this.temp = [];
        this.urls = [ 'url1', 'url2', 'url3', 'url4' ];
        var self = this;

        // make a $.get call for each URL and add
        _.each(this.urls, function(url) {
            $.get(url, { success: function(data) {
                console.log("Got partial collection from " + url);
                self.addPartial(data);

                // alternatively, just call "self.add(data);" here

            }, error: function(response) {
                console.log("Oops, the Ajax call failed for some reason... ignoring");
                self.completeCount ++;
                self.errorCount ++;
            } });
        });
    },

    // add a JSON array that contains a subset of the collection
    addPartial: function(data) {
        this.completeCount ++;
        var self = this;    

        // add each item to temp
        _.each(data, function(item) {
            self.temp.push(item);   
        });

        // if all have been received, then create the collection
        if (this.completeCount == this.urls.length) {
            this.reset(this.temp);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

这是一个小提琴,我$.get用一个只在短暂延迟后返回虚拟数据的方法替换.

回应评论

在它们进入时将响应添加到集合中可能更好(无论如何它都更容易). 这是一个更新的小提琴.