Sathya
Sathya

Reputation: 5308

Backbone - before route / view change event

I want to execute a method on a view before changing to some other view. For example.

var HomeView = Backbone.View.extend({  
......,   
close: function() {

}
});

var LoginView = Backbone.View.extend({  
......    
}
});

If my current view is "HomeView" and if i am going to switch to "LoginView", i need to execute close function in HomeView before changing to LoginView. Is there a way?

In other words, my view should execute close function automatically before it is going to be changed.

I have seen some of the stackoverflow's previous posts. They seems outdated Or not useful for this context.

Upvotes: 2

Views: 1596

Answers (3)

Blue
Blue

Reputation: 1

**HomeView.js**
var HomeView = Backbone.View.extend({  
initialize: function(){
},
close: function(){ //code }
});

var LoginView = Backbone.View.extend({  
 initialize: function(){
  (new HomeView).close();
  //code
 }
}
});

Upvotes: -1

pawel
pawel

Reputation: 36965

If you use Router to switch between views:

var HomeView = Backbone.View.extend({
    initialize : function(){
        /*
            router here references a global router object
            "route" event is triggered when any route has been matched; 
            if you want to call the close function only when navigating to login view you may use something like "route:login"
        */
        this.listenTo( router , "route", this.close );
    },
    close: function( router, route ) {
            /* becaouse route event will be called every time the route changes. 
               it will also be called when navigating to the HomeView. 
               use the route argument to filter this event out 
            */
            if( route != 'home' ){
               // close
            }
    }
    ....
});

Upvotes: 3

Blue
Blue

Reputation: 1

**HomeView.js**
var HomeView = Backbone.View.extend({  

});

var LoginView = Backbone.View.extend({  
......    
}
});

function close()
{
 //code
}

now in router or before calling another view just call close() method.

hope that helps.....

Upvotes: 0

Related Questions