Examples

Lets build a simple fake guestbook for users to sign (You haven't seen one for a while, did you?). Nothing is persisted and saved to database - so feel free to sign it.



For our fake guestbook to work we had to write following html:


            
        

Our guestbook Simple view type is defined like so:


            var Guestbook = SimpleView.extend({
                initialize: function() {
                    this.$entryList = this.$('.entryList');
                    this.$input = this.$('.entryInput');
                },
                events: {
                    'submit form': 'handleSubmitEntry',
                    'resize window': 'updateView',
                },
                handleSubmitEntry: function(e) {
                    e.preventDefault();
                    var message = this.$input.val();
                    message.length && this.addEntry(message);
                    this.$input.val('');
                },
                addEntry: function(message) {
                    var entryView = this.addView(new GuestbookEntry({message: message}));
                    entryView.$el.prependTo(this.$entryList);
                },
                updateView: function() {
                    this.$el.toggleClass('small', this.$window.width() < 500);
                }
            });

            new Guestbook({$el: '.guestbook'});
        

Guestbook entries are written as follows:


            var GuestbookEntry = SimpleView.extend({
                defaults: {
                    className: 'guestbookEntry',
                    btnRemoveClass: 'removeEntry'
                },
                initialize: function(options) {
                    this.options = $.extend({}, this.defaults, options);
                    this.$el = $(this.template(this.options));
                },
                events: {
                    'click .{{this.options.btnRemoveClass}}': 'remove',
                    'one:click .message': 'clickMessage'
                },
                template: function(data) {
                    return '<div class="' + data.className + '">\
                                <span class="message">' + data.message + '</span>\
                                <button class="' + data.btnRemoveClass + '">×</button>\
                            </div>';
                },
                clickMessage: function(e) {
                    console.log($(e.target).text());
                }
            });