Search code examples
javascriptjquerybackbone.jsbackbone-views

Backbone: Can't remove a view when call method remove()


I have tried to remove a view that contains makers that are rendered in map. When I click a button, the event click .ver is being activated, but nothing happens and I receive the following error: Uncaught TypeError: undefined is not a function. I don't know what I'm doing wrong.

My code:

ev.views.Home_Eventos = Backbone.View.extend({
    initialize: function(map){
        this.template = _.template(ev.templateLoader.get('home_list_eventos'));
        this.map = map;
        //console.log(this.map);
        this.render(this.map);
    },

    events: {
        'click .ver' : 'teste'  
    },

    teste: function(){
        ev.views.Markers.remove();
    },

    render: function(map){
        var that = this;
        that.map = map;
        var imagens = new ev.models.ImagemCollection();
        imagens.fetch({
            success: function(){
                that.$el.html(that.template({imagens: imagens.models}));
                var marcadores = imagens.models;
                    setTimeout(function() {
                    that.local(that.map);
                    var marcadores = new ev.views.Markers(that.map);
                }, 0);
                return that;
            }
        });
    }

});

ev.views.Markers = Backbone.View.extend({
    initialize: function(map){
        this.map = map;
        this.render(this.map);
    },

    render: function(map){
        var that = this;
        var imagens = new ev.models.ImagemCollection();
        imagens.fetch({
            success: function(){
                var marcadores = imagens.models;
                    setTimeout(function() {
                    _.each(marcadores, function(marcador){
                        var myLatlng = new google.maps.LatLng(marcador.get('latitude'),marcador.get('longitude'));
                        var marker = new google.maps.Marker({
                            position: myLatlng,
                            map: that.map,
                        });

                    });
                }, 0);

                return that;
            }
        });
    }

});

Solution

  • You need to keep a reference to the views you want to remove. For example, you have:

    var marcadores = new ev.views.Markers(that.map);
    

    you could save a reference on your view by doing this instead:

    that.marcadores = new ev.views.Markers(that.map);
    

    and then in your event handler,

    teste: function(){
        this.marcadores.remove();
    },
    

    This will destroy the Marker view that you've created but may not clean up the Google Maps markers managed by that view.