【问题标题】:Backbone collection not updating with JSONP request不使用 JSONP 请求更新主干集合
【发布时间】:2013-01-25 16:30:59
【问题描述】:

我最近刚开始使用 Backbone.js,我正在开发一个应用程序,现在使用 Brunch 向外部 API 发出 JSONP 请求以填充我的集合和模型。我正在关注这些以前的帖子(thisthis)关于使用 Backbone 执行 JSONP 请求,但由于某种原因,我的集合仍然没有获取数据。

我的模型(app/models/model.js):

module.exports = Backbone.Model.extend({
});

我的收藏(app/models/collection.js):

var Post = require('./model');

module.exports = Backbone.Collection.extend({
    model: Post,
    url: "http://somedata.com/api/posts/list/stuff",
    sync: function(method, model, options) {  
        options.timeout = 10000;
        options.dataType = "jsonp";
        options.jsonp = "JSONPcallback";        
        return Backbone.sync(method, model, options);
    },
    parse: function(response) {
        if (response) {
            var parsed = [];
            for(var i = 0; i < response.results.length; i++) {
                parsed.push(response.results[i][0]);
            }

            return parsed;
        }
    }
});

然后,在 app/application.js 中的初始化方法中,我通过以下方式调用它:

var Category = require('models/collection');
this.cat = new Category();
this.cat.fetch();

现在,当我查看 console.log 中的 parse 函数时,我看到正在获取数据,因此请求成功通过。但是,当我的视图被渲染并且我在 app/views/view.js 中执行 console.log(application.cat.models) 时,我什么也得不到——为什么会这样?我的模型/集合上的代码有什么问题吗?

此外,JSONP 数据具有以下格式,这就是为什么循环遍历 for response.results[i][0] 并返回一个包含所有数据的数组,这应该可以解决问题,对吧?

{"results":[
  {"0":{"id":xxx,"title":xxx,"link":xxx},
   "description":xxx},
  {"0":{"id":xxx,"title":xxx,"link":xxx},
   "description":xxx},
  {"0":{"id":xxx,"title":xxx,"link":xxx},
   "description":xxx},...
]}

非常感谢任何帮助...

【问题讨论】:

  • collection.fetch() 是异步请求,需要回调才能查看数据
  • 非常感谢,好点子 - backbonejs.org/#Collection-fetch 也这么说,而且它不应该在页面加载时使用。它说 reset() 用于在初始页面加载中增强集合。那么,我应该在 application.js 中对这些数据进行 ajax 请求,并将 this.cat.reset() 作为成功回调?

标签: javascript ajax backbone.js jsonp brunch


【解决方案1】:

我这里有 2 个 cmets:

  1. 我看到您将模型和集合都命名为 module.exports ,一种常见的做法是将模型设为单数 (module.export) 并将这些模型的集合设为复数 module.exports ,只需常规做法,否则没有任何“错误”

  2. 您的代码中可以有 2 个回调,当集合完成获取数据(异步事件)时,还考虑将 module.exports 作为您的集合,

A.你可以这样做:

module.exports.fetch({
success : function(data){
console.log(JSON.stringiy(data));
//do remaining programming here
}
});

B.你可以有一个reset 的事件监听器,从文档here 中,集合在完成获取时触发一个reset 事件,所以可以像这样在集合上添加一个事件监听器:

module.exports.on('reset',function(data){
console.log(JSON.stringify(data));
//do remaining programming here
},this);

【讨论】:

  • 谢谢,我在调用 fetch() 之前已经完成了 this.collection.bind('reset', this.collectionView.render) 并且成功了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多