0

所以我的 Backbone.js 代码正在获取 JSON ......我试图在 fetch 方法的成功回调中简单地控制模型,但我只是返回 [r,r,r] 而不是 [object,object,object ]。拔我的头发...

var Person = Backbone.Model.extend();
var PersonCollection = Backbone.Collection.extend({    
    model : Person,
    url: 'js/names.json',
    parse: function(data) {
        console.log(data); // <--- this will return what I am looking for
        return data;
    }
});
var PersonView = Backbone.View.extend({
    initialize: function(){
        var self = this;
        self.collection = new PersonCollection();
        self.collection.fetch({success: function() {
            console.log(self.collection.models); // <-- how do I get it here?
        }});
    }                                     
});                               
var newView = new PersonView();

JSON

[
    { "name": "Linda", "birthYear": 1947},
    { "name": "Kat", "birthYear": 1977},
    { "name": "Jen", "birthYear": 1989}
]

编辑:当我在集合中的自定义解析方法中控制台记录数据时,我想要在获取之后得到同样的东西。请参阅上面代码中的注释

4

3 回答 3

0

Looking here suggests that your callback function will get passed the items, e.g.

users.fetch({
      success: function (users) {
        var template = _.template($('#user-list-template').html(), {users: users.models});
        that.$el.html(template);
      }
    })

So maybe a tweak to your callback will help...

于 2013-11-05T23:15:39.713 回答
0

你越来越糊涂了。集合中的模型是围绕您的记录的主干模型,而不是直接类似于您提供给集合的 JSON 的任何东西。如果你想要,考虑一下console.log(JSON.stringify(self.collection))

于 2013-11-05T22:41:31.707 回答
0

我尝试了这段代码,现在添加到 toJSON 记录解析函数记录的相同对象。如果您没有得到相同的输出,则代码的其他部分可能有问题。

var Person = Backbone.Model.extend();
var PersonCollection = Backbone.Collection.extend({
    model : Person,
    url: 'js/names.json',
    parse: function(data) {
        console.log(data); // <--- this return array of name objects
        return data;
    }
});
var PersonView = Backbone.View.extend({
    initialize: function(){
        var self = this;
        self.collection = new PersonCollection();
        self.collection.fetch({success: function() {
            console.log(self.collection.toJSON()); // <-- even this return array of name objects
        }});
    }
});
var newView = new PersonView();
于 2013-11-06T06:15:04.637 回答