如何让Backbone.ajax返回成功数据

Jas*_*son 5 javascript json backbone.js

我试图让Backbone.ajax返回集合"集合".我需要在程序的另一部分中使用Model.

我想使数据与ajax方法处于同一级别.

Backbone.ajax({
    dataType: "jsonp",
    url: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=25",
    data: "",
    success: function(val){ val
        var Model = Backbone.Model.extend({});
        var Collection = Backbone.Collection.extend({
            model:Model
        });
        collection = new Collection(val);
        console.log(collection);
    }
});
Run Code Online (Sandbox Code Playgroud)

Jay*_*ayC 12

不要!您的连接的存在几乎永远不会取决于任何"ajax"调用!你需要正义之举集合的定义和实例你的Ajax成功方法的AJAX调用之前的地方外,再reset或者add成功的方法或类似的东西内搜集.您需要外部它,以便您可以在实际需要数据之前定义所有视图绑定等; 否则你最终会陷入一团糟 - 你试图通过使用Backbone 来避免这种混乱.

//definitions
var MyModel = Backbone.Model.extend({});
var MyCollection = Backbone.Collection.extend({
    model:Model
});

//wherever you need a collection instance
collection = new MyCollection();

//wherever you need to do the ajax
Backbone.ajax({
    dataType: "jsonp",
    url: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=25",
    data: "",
    success: function(val){
        collection.add(val);  //or reset
        console.log(collection);
    }
});
Run Code Online (Sandbox Code Playgroud)