shabashj
12/11/2016 - 9:48 AM

Backbone

Backbone

var Framework = Backbone.Model.extend({});
var Angular = new Framework();


//Lets create simple view
var HomeView = Backbone.View.extend({
    // This will tell to the view where to put/render my $el
    el: 'body',

    // this run when view constractor called
    initialize: function() {
        //render for me on initialization
        this.render();
    },

    // Rendering function - append to my object view some html
    // Rendering will not run by itself. Somebody should call it.
    render: function() {
        this.$el.empty();
        this.$el.append("<h1>My Backbone app</h1>");
        // When returning "this" it allows to chain methods and get access inside element
        return this;
    }
});

//var myView = new HomeView();

//List view example 
var ListView = Backbone.View.extend({
    // which html tag i want to create
    tagName: 'ul',

    initialize: function() {},

    render: function() {
        this.$el.empty();
        this.$el.append("<li>List Item</li>");
        this.$el.append("<li>List Item</li>");
        this.$el.append("<li>List Item</li>");
        this.$el.append("<li>List Item</li>");

        return this;
    }
});

// Let's chain list view to Home View
var HomeViewWithList = Backbone.View.extend({
    el: 'body',

    initialize: function() {
        this.render();
    },

    render: function() {
        this.$el.empty();
        this.$el.append("<h1>My Backbone app</h1>");

        this.listView = new ListView();
        this.$el.append(this.listView.render().el);
        return this;
    }
});

//var test = new HomeViewWithList();

// TEMAPLTES

//List view example with template
var ListViewFromTemplate = Backbone.View.extend({
    tagName: 'ul',

    initialize: function() {
        this.template = _.template("<li><%= value %></li>");
    },

    render: function() {
        this.$el.empty();
	// Add to me(ul) templated li 
        this.$el.append(this.template({
            value: "Hello world"
        }));

        return this;
    }
});


var HomeViewWithListFromTemplate = Backbone.View.extend({
    el: 'body',

    initialize: function() {
        this.render();
    },

    render: function() {
        this.$el.empty();
        this.$el.append("<h1>My Backbone app</h1>");

        this.listView = new ListViewFromTemplate();
        this.$el.append(this.listView.render().el);
        return this;
    }
});

var test = new HomeViewWithListFromTemplate();