lorenos lorenos - 1 month ago 4
Javascript Question

How to send collection to another view?

Is there anyway to send backbone collection to another view without listenTo methods, to send it like an array or something else.

Im doing the fetch in the initialize function and then putting the collection in my array is that bad?

this.userModels = [];

this.collectionUser = new app.types.Users();
this.collectionUser.fetch();

this.userModels.push(this.collectionUser);


Im trying to send it like an array but on refreshing my web page sometimes im getting this

this.options child {length: 15, models: Array[15], _byId: Object, _listenId: "l4", _events: Object…}


and sometime getting with zero values

this.options child {length: 0, models: Array[0], _byId: Object, _listenId: "l4", _events: Object…}


So i wanna send my collection without listenTo method if it's possible.

Answer

Yes you can send everything with js and use initialize for that view. In your view you need to declare initialize function like this.

var someView = Backbone.View.extend({
    template: _.template('some html file'),
    initialize: function(options){
        this.collection = options.collection
    },
    events: {
        'click .someclass': 'doSomthing',
        'click #someId': 'doSomthingElse'
    },
    doSomthing: function(event){
         event.preventDefault();
         var that = this;
         that.collection.fetch({
            success: function(){
                that.$('element').append(that.collection);
            }
        });
    },
    render: function(){
        var that = this;
        that.$el.html(that.template);
        return this;
    }
});

And when u make new instance of your view need pass your collection as argument.

this.collectionUser = new app.types.Users();
this.view = new someView({collection: this.collectionUser});

This is it