BB: Using setElement to create a Backbone View
by kyllle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone-localstorage.js/1.1.16/backbone.localStorage-min.js"></script>
<div class="js-ctn">
<div class="my-view">
<h3>Statically rendered view</h3>
<p>Initially this view is rendered to the DOM by default via the server, we then want to take over this view and make the app dynamic. Backbone setElement comes in handy for this.</p>
<button class="js-trigger">Click</button>
</div>
</div>
CSS
@import url(http://fonts.googleapis.com/css?family=Roboto:300,400,500);
* {
-webkit-font-smoothing: antialiased;
}
body {
font-family: Roboto;
padding: 16px;
line-height: 1.5;
font-weight: normal;
color: #ccc;
background: #292929;
font-size: 18px;
}
h1, h2, h3 {
font-weight: normal;
}
.pg-heading {
margin-bottom: 0;
}
a {
color: #95baf6;
transition: opacity .3s;
}
a:hover {
opacity: 0.75;
}
button {
outline: none;
border: none;
padding: 8px 16px;
background: #2196F3;
color: white;
transition: background .3s;
}
JavaScript
console.clear();
// Classes
var View = Backbone.View.extend({
events: {
'click .js-trigger': 'onBtnClick'
},
onBtnClick: function(event) {
event.preventDefault();
$(event.currentTarget).text('View live');
}
});
// Setup
var newView = new View();
newView.setElement($('.my-view'));
// Check this
/*
https://snipcart.com/blog/how-to-use-webpack-for-killer-refactoring
var AddMessageView = require('./views/addmessageview');
var MessagesView = require('./views/messagesview');
var MessagesCollection = require('./collections/messagescollection');
var messages = new MessagesCollection();
new AddMessageView({collection: messages}).setElement('#add-message');
new MessagesView({collection: messages}).setElement('#todos');
*/