backbone state

by paulftw

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<script type="text/template" id="login-tpl">
  <h1>Login Page</h1>
      <h3>E-mail</h3>
  <input type=text id=email></input>
</script>

<script type="text/template" id="list-tpl">
  <h1><%- title %></h1>
  <a href="#">Find New</a>
  <h3>Obj List</h3>
</script>

<div id="appview"></div>

<a href="#" id=doit>doIt!</a>

CSS

#appview {
    border: 3px dashed #0a0;
    border-radius: 4px;
    margin: 10px;
    padding: 12px;
    width: 600px;
    height: 300px;
}

.page h1 {
    margin: 0 auto;
    text-align: center;
    box-shadow: none;
}

.page input {
    height: 36px;
    border-radius: 7px;
    border: 1px solid #333;
    padding: 0 8px;
    font-size: 18px;
    box-shadow: 0 0 0 rgba(0, 0, 0, .2);
}

JavaScript

$(function() {
    window.loginState = new Backbone.Model({
        email: 'imaloginpage',
        userToken: null,
    });
    var appModel = new Backbone.Model({
        curpage: 'login',
        pages: {
            'login': new PageView({
                model: window.loginState,
            }),
            'inapp': new PageView({
                model: new Backbone.Model({
                    title: 'icanseeapp',
                    error: 1,
                }),
                template: 'list-tpl',
            }),
        },
    });
    var app = new MyAppView({
        model: appModel,
    });

    $('#doit').click(function() {
        appModel.set('curpage', 'inapp');
    });
    app.render();
});

window.MyAppView = Backbone.View.extend({
    initialize: function() {
        this.model.bind('all', this.render, this);
        this.el = $('#appview');
    },
    render: function() {
        this.el.html("");
        var page = this.model.get('pages')[
                this.model.get('curpage')];
        this.el.append(page.render().el);
        return this;
    },
});
        
        
window.PageView = Backbone.View.extend({
    initialize: function(options) {
        var template = options.template || 'login-tpl';
        this.tpl = _.template($('#' + template).html());
    },
    render: function() {
        this.el.innerHTML = this.tpl(this.model.toJSON());
        return this;
    },
    template: 'login-tpl',
    className: 'page',
    tagName: 'div',
});
    
window.Page = Backbone.Model.extend({});