Simple view

Organize your application interface with lightweight javascript view components. Simple view works pretty much like a augmented Backbone view with no large dependencies. Weighs around 1.5 KB.

Simple view allows you to delegate or bind events to current element context with a simple declarative syntax. Event strings can be dynamically configured with injected variables. One time events are configured with simple prefix on event string . You can listen to window and document events and be sure that all handlers will be cleaned up upon view removal.

Every Simple view instance can have sub-views and be used as container of views (collection view). Controller and component views can be easily composed if that is how you want your application to be structured. Choose your view hierarchy as it suits your project needs.

Simple view works great with server side rendered html. There is no requirement for client side templating or rendering of any kind.

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({
                events: {
                    'submit form': 'submitEntry'
                },
                submitEntry: function(e) {
                    e.preventDefault();
                    var $input = this.$('.entryInput');
                    var message = $input.val();
                    message.length && this.addEntry(message);
                    $input.val('');
                },
                addEntry: function(message) {
                    var entryView = this.addView(new GuestbookEntry({message: message}));
                    entryView.$el.prependTo(this.$('.entryList'));
                }
            });

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

Guestbook entries are written as follows:


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

Api and options

SimpleView.extend(prototypeProperties, [staticProperties])

Used to define view types / constructor functions. Define prototype methods for view via object hash. Static properties are optional.


initialize(options)

Define initialize function in prototype properties if you need to do some logic on view startup. Will receive all arguments from constructor.


assignOptions(boolean)

If defined user passed options will be merged with defaults and written to viewInstance.options. False by default.


defaults(object | function)

Define view default options with object hash or function return object.


optionRules(object)

Options provided by view defaults and and constructor parameters can be type checked as defined here.


            optionRules: {
                instrument: String,
                age: {type: Number, default: 18, validator: function(age) {
                    return age >= 18;
                }},
                mentor: {type: Person, required: false}
                url: [String, Function]
            }
        

events(object | function)

Declare events with object hash or custom function in prototype properties.


            events: {
                'click .selector': 'handler',
                'click {{this.someVariable}}': 'handler', // variable will be injected
                'one:submit form': 'oneSubmit', // handler will run only once
                'resize window': 'onWindowResize',
                'keyup document': 'onDocumentKeyup'
            }
        

addDismissListener(listenerName)

When escape key is pressed or element outside view is clicked view.listenerName will be run.


removeDismissListener(listenerName)

Remove dismiss listener identified via listenerName.


delegatedEvents: true | false

Events are delegated to view by default. If you want to bind them directly to elements (to avoid excessive bubbling on views with complex dom tree) set "delegatedEvents" to false.


addView(viewInstance)

Adds view instance to sub view registry. This binding enables effective cleanup of container views.


mapView(selector, View, [params])

Create View instance with first element inside current view found via selector. Returns mapped instance.


mapViews(selector, View, [params])

Map View instances to all elements inside current view found via selector. Returns mapped instances array;


removeViews()

Removes all registered sub views.


$(selector)

Alias for this.$el.find(selector);


trigger(eventName, [data])

Trigger custom event and optionally provide data to handler callback.


on(eventName, callback)

Subscribe to custom view events


off([eventName, [callback]])

Removes listeners to custom view events.


listenTo(publisher, eventName, callback)

Listen to other object events.


stopListening([publisher, [eventName, [callback]]])

Removes listeners to custom publisher events.


remove()

Removes view from DOM and does cleanup of all bound events.

Installation

SimpleView is packaged as UMD library so you can use it in CommonJS and AMD environment or with browser globals.


            // install via npm
            npm install jquery-simple-view --save

            // if you use bundler
            var SimpleView = require('jquery-simple-view');

            // or just using browser globals
            var SimpleView = window.SimpleView;
        

For browser usage browse dist folder - if working with build tools go with src folder. Download library files from github repo, get them via bower (bower install simple-view) or via npm (npm install jquery-simple-view)

Fork me on GitHub