鈍足ランナーのIT日記

走るのが好きな5流のITエンジニアのブログ。

趣味の範囲は広いけど、どれも中途半端なクソブロガー楽しめるWebアプリを作ってあっと言わせたい。サーバーサイドPerl(Mojolicious)、クライアントサイドVue.js。Arduinoにも触手を伸ばす予定。

Backbone.jsで複数のビューをひとまとめにして扱いたい

Backbone.jsで複数のビューをひとまとめにして扱いたい

タブメニューで、メニューを選ぶとcontentタグの内容を動的に切り替えて 使う。Backbone.jsのルーターでビューの切り替え部分をコーディングしています。 参考にした記事はこちらhow-to-switch-views-using-backbonejs

<div id="content"></div>
var ApplicationRouter = Backbone.Router.extend({

    initialize: function(el) {
        this.el = el;

        this.calendarView = new ContentView({template: '#calendar'});
        this.calendarHeaderView = new ContentView({template: '#calendarHeader'});
        this.readmeView = new ContentView({template: '#readme'});
        this.notFoundView = new ContentView({template: '#not-found'});
    },

    routes: {
        "": "main",
        "readme": "readme",
        "*else": "notFound"
    },

    currentView: null,

    switchView: function(view) {
        if (this.currentView) {
            // Detach the old view
            this.currentView.remove();
        }

        // Move the view element into the DOM (replacing the old content)
        this.el.html(view.el);

        // Render view after it is in the DOM (styles are applied)
        view.render();

        this.currentView = view;
    },

    /*
    * Change the active element in the topbar
    */
    setActiveEntry: function(url) {
        // Unmark all entries
        $('li').removeClass('active');

        // Mark active entry
        $("li a[href='" + url + "']").parents('li').addClass('active');
    },

    main: function() {
// ここでは、カレンダービューとカレンダーヘッダービューを一まとめにして扱いたい
        this.switchView(this.calendarView);
        this.setActiveEntry('#main');
    },

    readme: function() {
        this.switchView(this.readmeView);
        this.setActiveEntry('#readme');
    },

    notFound: function() {
        this.switchView(this.notFoundView);
    }

});

問題は、複数のビューからなるビューを作りたいってこと。 さて、どうすればいいのだろうか?

結局、うーん。私には難しすぎるようで、今回は諦めました。 また、そのうちリベンジ。