Backbone Tutorial: Views

By Xah Lee. Date:

this page is work in progress

// Backbone model
let Sidebar = Backbone.View.extend({
  promptColor: function() {
    let cssColor = prompt("Please enter a CSS color:");
    this.set({color: cssColor});
  }
});

window.sidebar = new Sidebar;

sidebar.on('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

sidebar.set({color: 'white'});

sidebar.promptColor();

this is a basic intro to Backbone's View object. First see Backbone Tutorial

views is the majority of code

define custom view types

instantiating view interfaces

here's a complex Backbone shit

// Backbone model
let Sidebar = Backbone.Model.extend({
  promptColor: function() {
    let cssColor = prompt("Please enter a CSS color:");
    this.set({color: cssColor});
  }
});

window.sidebar = new Sidebar;

sidebar.on('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

sidebar.set({color: 'white'});

sidebar.promptColor();

creating a view

creating a view

// example of creating a view

let DocumentRow = Backbone.View.extend({
  tagName: "li",
  className: "document-row",
  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  },

  render: function() {
 //   }
});

view objects can also have a inheritance hierachy, just like model objects

the .el property

each view object is associated with a dom element. you can access it by the property “el”

existing views

attaching a view

<div id="x62">something</div>
let V = Backbone.View.extend({});
let v = new V({el: "#x62"});
v.$el.css("background-color", "yellow");

Backbone Example, View, attaching

passing a model to view constrcutor

let V = Backbone.View.extend({});
let v = new V( "model":‹model object›);

let myModel = new Backbone.Model();

myModel.set("content", "some");

let = myView = new Backbone.View({
    model: myModel,
    className: "model-object"
});

$("body").propend(myView.elll);

If you have a question, put $5 at patreon and message me.

Backbone

  1. Basics
  2. View
  3. Route