Skip to content

Instantly share code, notes, and snippets.

@droberts-sea
Last active November 28, 2016 00:12
Show Gist options
  • Save droberts-sea/c415d22e2f3ab68ad22eaffbf6522020 to your computer and use it in GitHub Desktop.
Save droberts-sea/c415d22e2f3ab68ad22eaffbf6522020 to your computer and use it in GitHub Desktop.
Ada C6 Backbone Views Checkin 2
import $ from 'jquery';
import _ from 'underscore';
import Backbone from 'backbone';
var taskData = [
{
title: 'Mow the lawn',
description: 'Must be finished before BBQ on Sat afternoon'
}, {
title: 'Go to the Bank',
description: 'Need to make a transfer'
}, {
title: 'Tune the Piano',
description: 'High C is missing or something???'
}
];
var TaskView = Backbone.View.extend({
initialize: function(options) {
this.task = options.task;
this.template = options.template;
},
render: function() {
var html = this.template({task: this.task})
this.$el.html(html);
// Enable chained calls
return this;
}
});
var TaskListView = Backbone.View.extend({
initialize: function(options) {
// Store a the full list of tasks
this.taskData = options.taskData;
// Compile a template to be shared between the individual tasks
this.taskTemplate = _.template($('#task-template').html());
// Keep track of the <ul> element
this.listElement = this.$('.task-list');
// Create a TaskView for each task
this.cardList = [];
this.taskData.forEach(function(task) {
var card = new TaskView({
task: task,
template: this.taskTemplate
});
this.cardList.push(card);
}, this); // bind `this` so it's available inside forEach
},
render: function() {
// Make sure the list in the DOM is empty
// before we start appending items
this.listElement.empty();
// Loop through the data assigned to this view
this.cardList.forEach(function(card) {
// Cause the task to render
card.render();
// Add that HTML to our task list
this.listElement.append(card.$el);
}, this);
return this; // enable chained calls
}
});
$(document).ready(function() {
var application = new TaskListView({
el: $('#application'),
taskData: taskData
});
application.render();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/foundation/6.2.4/foundation.min.css">
<link rel="stylesheet" href="styles/index.css">
</head>
<body>
<main class="row" id="application">
<section class="small-12 columns">
<h1>Task List</h1>
</section>
<ul class="task-list small-12 large-6 columns end">
</ul>
</main>
<script type="text/template" id="task-template">
<li class="task">
<h2>
<%- task.title %>
</h2>
<p>
<%- task.description %>
</p>
</li>
</script>
<script src="/app.bundle.js" charset="utf-8"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment