问题描述:

I have a backbonejs application that contains a router file and some views , and also i'm using requirejs to add views to routes and add templates to views. here is my codes :

routes.js

var AppRouter = Backbone.Router.extend({

routes: {

"": "getLogin",

"login": "getLogin",

"register": "getRegister",

"forget-password": "getForgetPassword"

},

getLogin: function() {

require(['views/auth/loginView'], function(view) {

view = new this.LoginView();

});

},

getRegister: function() {

require(['views/auth/registerView'], function() {

view = new this.RegisterView();

});

},

getForgetPassword: function() {

require(['views/auth/forgetPasswordView'], function() {

view = new this.ForgetPasswordView();

});

},

});

var route = new AppRouter();

Backbone.history.start();

loginView.js

var LoginView = Backbone.View.extend({

el: '#wrapper',

initialize: function() {

NProgress.start();

this.render();

},

render: function() {

require(['text!partials/auth/login.html'], function(t) {

var json = { title: 'title', formName: 'frmLogin' };

var template = _.template(t);

$('#wrapper').html(template(json));

});

NProgress.done();

},

events: {

"click #btnLogin": "login"

},

login: function(e) {

e.preventDefault();

alert('some message');

}

});

also registerView.js and forgetPasswordView.js are similar to loginView.js.

now! when i change routes multiple times and hit #btnLogn it fires alert('some message'); function multiple times...!

网友答案:

Have you tried un-delegating the events in the view, on route change?

You could override the route method (annotated source) in your AppRouter and run it before each route is rendered.

route: function(route, name, callback) {
    view.undelegateEvents();
    return Backbone.Router.prototype.route.apply(this, arguments);
}

Note: Just an idea, not tested with your code

相关阅读:
Top