backbonejs-hello-world /js/coffee/helloworld5.coffee

Language CoffeeScript Lines 83
MD5 Hash f4455f2b46adc436e222298a7001d1fb
Repository https://bitbucket.org/digitaltrike/backbonejs-hello-world.git View Raw File
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
Backbone.sync = (method, model, success, error) ->
  success()

  # Model
window.Item = Backbone.Model.extend(defaults:
  part1: "hello"
  part2: "world"
)

# Collection
window.List = Backbone.Collection.extend(model: Item)

# Item View
window.ItemView = Backbone.View.extend(
  tagName: "li" # name of tag to be created

  events:
    "click span.swap": "swap"
    "click span.delete": "remove"

  initialize: ->
    _.bindAll @

    @model.bind "change", @render
    @model.bind "remove", @unrender

  render: ->
    @$el.html _.template $("#template_helloworld_item2").html(),
      part1: @model.get "part1"
      part2: @model.get "part2"

    @

  unrender: ->
    @$el.remove()

  swap: ->
    swapped =
      part1: @model.get "part2"
      part2: @model.get "part1"

    @model.set swapped

  remove: ->
    @model.destroy()
)

# List View
window.ListView = Backbone.View.extend(
  events:
    "click button#add": "addItem"

  initialize: ->
    _.bindAll @

    @collection = new List()
    @collection.bind "add", @appendItem # collection event binder
    @counter = 0

    @render()

  render: ->
    self = @

    @$el.html _.template $("#template_helloworld2").html(), {}

    @collection.each (item) ->
      self.appendItem item
    , @

    $(".backbone").html @$el

  addItem: ->
    @counter++
    item = new Item()
    item.set part2: item.get("part2") + @counter # modify item defaults
    @collection.add item

  appendItem: (item) ->
    itemView = new ItemView(model: item)
    $("ul", @$el).append itemView.render().$el
)
Back to Top