Backbone app

by someprimetime

HTML

<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<button id="add-product">Add Product</button>
<button id="show-products">Show Products</button>
Total Products: <span id="total_product_count"></span>

<ul id="product-list" style="display: none">
    <li>Mac</li>
    <li>Clinuque</li>
    <li>Sugarpill</li>
</ul>

JavaScript

(function($) {
    Product = Backbone.Model.extend({
        // Create a model to hold product atribute
        name: null
    });

    Products = Backbone.Collection.extend({
        //This is our Products collection and holds our Product models
        initialize: function(models, options) {
            this.bind('add', options.view.addProductLi);
            this.bind('show', options.view.showProducts);
            //Listen for new additions to the collection and call a view function if so
        }
    });

    ProductView = Backbone.View.extend({
        el: $('body'),
        
        initialize: function() {
            // create a products collection when the view is initialized
           //passing it a reference to this view to create a connection between the two
            this.products = new Products(null, {
                view: this
            });
            this.updateCount();
        },

        events: {
            'click #add-product': 'addProducts',
            'click #show-products': 'showProducts'
        },

        addProducts: function() {
            var product_name = prompt('What is the product?');
            var product_model = new Product({
                name: product_name
            });
            //Add a new product model to our product collection
            this.products.add(product_model);
            this.updateCount();
        },

        showProducts: function() {
            if ($('#product-list').is(':hidden')) {
                $('#product-list').show();
                $('#show-products').text('Hide Products');
            } else {
                $('#product-list').hide();
                $('#show-products').text('Show Products');
            }
        },
        updateCount: function() {
            var count = Number($('#product-list li').length);
            $('#total_product_count').text(count);
        },

        addProductLi: function(model) {
            //The parameter passed is a reference to the model...