HTML in Backbone Model

by verashn

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<div id="result">
    <div class="display"></div>
    <a href="#" class="change">change model</a>
</div>

CSS

body {
    font-family: Helvetica, Arial, sans-serif;
}

.model-display {
    background: black;
    padding: 10px;
    margin: 10px 0;
    color: white;
}

JavaScript

$(function(){
    AppModel = Backbone.Model.extend({
    });
    
    AppView = Backbone.View.extend({
        events: {
             "click .change": function(e) {
                 e.preventDefault();
                 this.model.set({ html: '<div class="model-display" style="background:' + this.randomColor() + '">Model HTML updated!</div>' });
                 return false;
             }
        },
        randomColor: function() {
            var r = Math.floor(Math.random() * 255),
                g = Math.floor(Math.random() * 255),
                b = Math.floor(Math.random() * 255),
                a = Math.round(Math.random() * 10)/10;
            return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
        },
        initialize: function() {
            this.render();
            this.model.on('change',this.render,this);
        },
        render: function() {
            $(this.el).find('.display').html(this.model.get('html'));
        }
    });
    
    var model = new AppModel({ html: '<div class="model-display">Initial model HTML</div>' });
    var view = new AppView({ 
        model: model, 
        el: '#result' 
    });
});