简体   繁体   中英

Backbone: not correct view after redirect

I am new to Backbone and have an issue from almous beginning wondering how to overcome issue with unexpected behavior of a main view. 1. I launch page and it looks okey. 2. I click button that lead me to different view and shows me it well. 3. I click "back" button and I see a blank page, but in DOM I can find some elements from previous view, but not visible.

Here is a piece of my router code (I hope this pieces will be enough):

home: function () {
    if (!app.leftMenuView) {
        app.leftMenuView = new app.views.LeftMenuView({
            el: $("#left_menu")
        });
    } else {
        app.leftMenuView.delegateEvents();
    }
    if (!app.homeView) {
        app.homeView = new app.views.HomeView({
            el: $("#main_container")
        });
    } else {
        app.homeView.delegateEvents();
    }
    if (!app.topMenuView) {
        app.topMenuView = new app.views.topMenuView({
            el: $("#top_menu")
        });
    } else {
        app.topMenuView.delegateEvents();
    }
},
search: function () {
    app.searchView = new app.views.SearchView({
        el: $("body")
    });
},

A piece of main html file:

<body>
     <div id="search-div"></div>
     ...
</body>

HomeView:

app.views.HomeView = Backbone.View.extend({
    initialize: function () {
        this.render()
    },
    render: function () {
        var self = this;
        $.get('/template/home.html', function (data) {
            self.$el.html(_.template(data)({}));
        });
        return this;
    },
});

A SearchView:

app.views.SearchView = Backbone.View.extend({
    events: {
        "click #left-arrow-icon": "toMainPage"
    },
    initialize: function () {
        this.render();
    },
    render: function () {
        var self = this;
        $.get('/template/searchView.html', function (data) {
            self.$el.html(_.template(data));
        });
        return this;
    },
    toMainPage: function () {
        Backbone.history.history.back();
    },
});

In the example provided, the search view, if rendered, will destroy the main html file content since the element provided is directly the body. In any case, if you go to search view, your home page will have been destroyed or will not be able to render anymore.

I would suggest an improved layout management :

  • separate elements per views
  • show/hide of root elements based on routes

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