Basic Model and View

by landau

HTML

<html>
    <body>
        <h1>Example 1</h1>
        <ul id="list1"></ul>
        <hr>
        <h1 id="ex2">example2</h1>
       
    </body>
</html>

CSS

h1 { 
    font-size: 18px; 
    font-weight: bold;
    text-decoration: underline;
}
li { font-size: 12px; }

JavaScript

(function() {
    "use strict";

    function Person(name, age) {
        try {
            if (typeof name !== 'string') {
                throw {
                    name: 'Person Error',
                    msg: 'name is not a String'
                };
            }
            if (typeof age !== 'number' || isNaN(age)) {
                throw {
                    name: 'Person Error',
                    msg: 'age is not a number'
                };
            }
            this.name = name;
            this.age = age;
        } catch (e) {
            console.error(e);
        }
    }

    Person.prototype = { // equivalent to separate function declarations
        reverseName: function(opts) {
            opts = opts || {
                silent: false
            };
            this.name = this.name.split('').reverse().join('');
            // inform any one listening to this event of the change
            // Pass the person as a parameter as well (the `this` after the event)
            if (!opts.silent) {
                $(this).trigger('change:name', this); // I use colons for namespacing
            }
        }
    };


    function PersonView(person) {
        try {
            if (!(person instanceof Person)) { // make sure this view has a Person object
                throw {
                    name: 'PersonView Error',
                    msg: 'invalid person object passed'
                };
            }
            this.$el = $('<li>'); // type of element for this view
            this.model = person;

            // listen to any name changes
            var self = this; // could use $.proxy too - but we need context access in this function
            $(this.model).on('change:name', function(person) {
                // since it's just a name change, just render the view
                self.render();
            });

        } catch (e) {
            console.error(e);
        }
    }

    PersonView.prototype = {
        render:...