1

我正在尝试使用集合来列出来自我的 api 的数据。但问题是,当我使用 forEach 时,我调用的函数 (addOne) 没有运行。

还有一些我怀疑工作错了。我的收藏是否应该在这样的模型下保存返回的 JSON?

Object -> models -> 0 -> attributes -> ...

我的观点:

s.Views.Fs = Backbone.View.extend({
    className: "",
    template: _.template("<%= name %>"),
    initialize: function() {

    },
    render: function() {
        this.collection.forEach(this.addOne, this);
    },
    addOne: function(f) {
        alert("a");
        var fV = new s.Views.PF({model: f});
        this.$el.append(fV.render().el);
    }
});

我的收藏:

s.Collections.FL = Backbone.Collection.extend({
    url: "api/fs/",
    model: s.Models.F,
});

我的模型:

s.Models.F = Backbone.Model.extend( {
    urlRoot: 'api/fs/',
    defaults: {
        ...
    },
    ...
    parse: function(response) {
            return response;
    },
});

我的路线(和应用程序):

var sApp = new (Backbone.Router.extend({
    f_a: function() {
        this.fL= new s.Collections.FL();
        this.fLV= new s.Views.Fs({collection: this.fL});
        this.fL.fetch();
        this.fLV.render();
    },
});
4

1 回答 1

3

监听事件是this.collection.on('add', this.addOne, this);在集合视图下进行的。这是测试代码的摘要(感谢提示'mu太短'):

看法

s.Views.Fs = Backbone.View.extend({
    className: "",
    template: _.template("<%= name %>"),
    initialize: function() {
        this.collection.on('add', this.addOne, this);
        this.collection.on('reset', this.render, this);
    },
    render: function() {
        this.collection.forEach(this.addOne, this);
    },
    addOne: function(f) {
        var fV = new s.Views.PF({model: f});
        fV.render();
        this.$el.append(fV.el);
    }
});

收藏

s.Collections.FL = Backbone.Collection.extend({
    url: "api/fs/",
    model: s.Models.F,
});

模型

s.Models.F = Backbone.Model.extend( {
    urlRoot: 'api/fs/',
    // No need to parse here.
});

路由器

var sApp = new (Backbone.Router.extend({
    f_a: function() {
        this.fL= new s.Collections.FL();
        this.fLV= new s.Views.Fs({collection: this.fL});
        this.fLV.render();
        $("#content").html(this.fLV.el);
        this.fL.fetch();
    },
});
于 2013-06-09T01:52:32.947 回答