Home > Articles > Programming > Graphic Programming

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

DOM Interactions

DOM Interactions

The problem with writing an article like this is that I want to show you everything. I want to teach you all that I know—a tricky task within my limit of 2,000 words. What I can do in that amount of space is give you a brief introduction to a topic and help to guide you down the path to understanding. Now let's look at some code.

Here's the Backbone view we'll test first:

# app/assets/javascripts/views/todos/todo_view.js.coffee
class OMG.Views.TodoView extends Backbone.View

  tagName: 'li'
  template: JST['todos/_todo']

    'change [name=completed]': 'completedChecked'
    'click .delete': 'deleteClicked'

  initialize: ->
    @model.on "change", @render

  render: =>
    $(@el).html(@template(todo: @model))
    if @model.get("completed") is true
      @$("[name=completed]").attr("checked", true)
    return @

  completedChecked: (e) =>
    @model.save(completed: $(e.target).attr("checked")?)

  deleteClicked: (e) =>
    if confirm("Are you sure?")

The OMG.Views.TodoView class is responsible for rendering a single instance of a Todo model to the page. It creates an li for the todo. If the todo is marked as completed, it makes sure that the checkbox next to its body is checked, and then it gives the body a CSS class of completed.

This view also listens for two events:

  • The first event is the checking/unchecking of the completed checkbox. When that occurs, the model's state is saved to the server, and the view re-renders itself to make sure that it's displaying the correct styling and information.
  • The second event occurs when someone clicks the delete button for the todo. The view displays a JavaScript dialog to confirm that the user really wants to destroy the todo. If the user confirms, the todo is destroyed, and the li is removed from the page. If the user doesn't confirm, nothing happens.

Next we need to test a few of these scenarios, but how?

  • + Share This
  • 🔖 Save To Your Account