Hilmi Erdem KEREN
Hilmi Erdem KEREN

Reputation: 1999

Backbone.js Collections View forEach doesn't work

I am trying to use collections to list my data coming from my api. But the problem is, when I use forEach, the function that I called (addOne) doesn't run.

There is also something I suspect working wrong. Should my collection save the returning JSON under the models like that?

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

My View:

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);
    }
});

My Collection:

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

My Model:

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

My Route (And App):

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();
    },
});

Upvotes: 1

Views: 3782

Answers (1)

Hilmi Erdem KEREN
Hilmi Erdem KEREN

Reputation: 1999

Listening for events is made by this.collection.on('add', this.addOne, this); under collection's view. Here is tested code's summary (Thanks for the tip 'mu is too short'):

VIEW

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);
    }
});

COLLECTION

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

MODEL

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

ROUTER

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();
    },
});

Upvotes: 3

Related Questions