Backbone - 在路由/视图更改事件之前

时间:2013-05-13 05:51:06

标签: backbone.js

我想在更改为其他视图之前在视图上执行方法。例如。

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

}
});

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

如果我当前的视图是“HomeView”,如果我要切换到“LoginView”,我需要在更改为LoginView之前在HomeView中执行close函数。有办法吗?

换句话说,我的视图应该在更改之前自动执行close函数。

我已经看到了一些stackoverflow以前的帖子。它们似乎过时或对这种情况没有用。

3 个答案:

答案 0 :(得分:3)

如果您使用路由器在视图之间切换:

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

答案 1 :(得分:0)

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

});

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

function close()
{
 //code
}

现在在路由器中或在调用另一个视图之前只调用close()方法。

希望有帮助.....

答案 2 :(得分:-1)

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

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