简体   繁体   中英

Backbone Error view is not a constructor

I try to make authentication app with Backbone.

My main.js. Where app starts :

require(['backbone', './views/AppView'], function (Backbone, AppView) {
    'use strict';

    var App = new AppView();
    App.render();
);

I've declared my libs before with requirejs. My AppView.js :

define (['backbone', 'Login', './home/HomeView', './login/LoginView'], function (Backbone, Login, HomeView, LoginView) {
'use strict';

var AppView = Backbone.View.extend({

    el : 'body',

    initialize : function () {
        console.log('init Appview');
        if (Login.isConnected()) {
            //Utilisateur connecté
            this.view = new HomeView();
        }
        else{
            //Utilisateur pas connecté
            this.view = new LoginView();
        }
    },

    render : function () {
        this.$el.html(this.view.render().$el);
        return this;
    }
});
return AppView;
});

Here i check if user is connected. If he is : AppView, If he isn't : LoginView. For the moment everything works good and the LoginView appear.

LoginView :

define(['backbone', 'underscore', 'jquery', 'requirejs-tpl!./../../../../resources/templates/login/LoginTemplate.html', 'Login', './../AppView'], function (Backbone, _, $, LoginTemplate, Login, AppView) {

'use strict';

var LoginView = Backbone.View.extend({

    initialize : function () {

    },

    render : function () {
        this.$el.html(LoginTemplate());
        return this;
    },

    events : {
        'click #btnConnect' : 'connect'
    },

    connect : function (event) {

        event.preventDefault();

        var login = $('#login').val();
        var password = $('#password').val();
        var ReponseLogin = Login.login(login, password);
        if(!ReponseLogin.connected){
            //Erreur
            $('#showErreur').html(ReponseLogin.erreur);
        }
        else{
            //Pas d'erreur, on affiche l'appli, AppView
            var App = new AppView();
            App.render();
        }
    }
});

return LoginView;

});

When i try to declare new AppView for to be reload on HomeView : "TypeError: AppView is not a constructor".

Someone can helps me ?

Thank

You are using a circular dependency - AppView requires LoginView, LoginView requires AppView. This is causing AppView to be null when referenced inside LoginView. There is a better explanation for this here : http://requirejs.org/docs/api.html#circular

You should probably refactor your design to not have this circular reference. If you find it necessary, you can use "require" again in the second module (LoginView) and pull in AppView (as shown in that link). But I strongly advise you rethink the design instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM