Barry
Barry

Reputation: 1587

How to clean views and models in Backbonejs

    movieDb.Router  = Backbone.Router.extend({
        routes:{
            '':         'landPage',
            'home':     'landPage',
            'login':    'login',
            'signup':   'signup'
        },

        landPage: function(p){
            $('div#homepage').empty();
        },

        login:  function(p){
            new loginViews(); // Calls its own model                
        },

        signup: function(p){
            new signupViews(); // Calls its own model
        }
    });

The problem is when coming from signup and calling login, it also calls the previous model requests(signup) resulting to login and signup request at the same time(my models are ajax requests), how can I remove the previously called models everytime I create a new request in my views.

Thanks.

Upvotes: 0

Views: 496

Answers (2)

Barry
Barry

Reputation: 1587

I just want to share how I solved this problem.(very basic approach, not sure if this is the best practice but it worked)

I extended the view with close function

    Backbone.View.prototype.close = function () {
        this.unbind();
        this.undelegateEvents();
    };

And created a showView function in my router to be called everytime I fire an event in my view.

    showView: function (view) {
        //destroy current view
        if(this.currentView !== undefined) {
            this.currentView.close();
        }

        //create new view
        this.currentView = view;
        this.currentView.delegateEvents();

        return this.currentView;
     }

Then call that showView function in my view

     addMovie:   function(p){
        this.showView(this.movieForm('add'));               
    }

Upvotes: 0

MarkKGreenway
MarkKGreenway

Reputation: 8754

The easiest way that i have found is to use Backbone.Marionette https://github.com/derickbailey/backbone.marionette which allows you to use separate regions for separate functions.
If you dont want to have another dependancy you can do that manually : http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/

but if you are seeing that a fetch on one model is calling a fetch on another then you probably have either a collision in names, or somehow a chaining of events that is causing the second fetch.

Upvotes: 1

Related Questions