1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- // Create a view class.
- const TodoView = Backbone.View.extend({
- tagName: 'article',
- id: 'todo-view',
- className: 'todo',
- // Underscore templating.
- //language=HTML
- template: _.template(`
- <h3 class="<%= status %>">
- <input type="checkbox"
- <% if (status === "complete") print("checked") %> />
- <%= description %>
- </h3>
- `),
- events: {
- // Generates this.$el.('h3", 'click', alertStatus).
- 'click h3': 'alertStatus',
- 'change input': 'toggleStatus',
- },
- // Backbone.
- initialize() {
- // Backbone on() takes (event, callback, context)
- this.model.on('change', this.render, this);
- // Or without an explicit context, use a bound function.
- // this.model.on('change', this.render.bind(this));
- this.model.on('destroy', this.remove, this);
- },
- // Handle on destroy.
- remove() {
- this.$el.remove();
- },
- // Handle "click h3"
- alertStatus() {
- // Noisy.
- // alert('Hey, you clicked the H3');
- },
- // Handle "change input".
- toggleStatus() {
- this.model.toggleStatus();
- },
- render: function () {
- const attributes = this.model.toJSON();
- const html = this.template(attributes);
- // Since this.el is a DOMElement, we can just wrap it with jQuery instead
- // of using a jQuery selector like $('#todo-view') or $('.todo').
- // This is better because it is id- and class- independent.
- // $(this.el).html(html);
- // Backbone even gives a shortcut: the $el property.
- this.$el.html(html);
- return this;
- },
- });
- function todoViewSingleExample(todoItem) {
- // Create a view instance.
- const todoView = new TodoView({ model: todoItem });
- // Build view.
- todoView.render();
- // console.log(todoView.el);
- // Apply to the DOM.
- $('#app').html(todoView.el);
- }
- $(function () {
- // Reuse the global item.
- // todoViewSingleExample(globalTodoItem);
- });
|