summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/views/my/cakes/edit_view.js.coffee
blob: 9da1698ef8f9992d659dbb60149b0087938cd55d (plain)
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
#= require views/my/cakes/thumbnail_view

class csx.Views.My.Cakes.EditView extends Marionette.CompositeView
  template : JST["templates/my/cakes/edit"]
  childView: csx.Views.My.Cakes.ThumbnailView
  childViewContainer: '.card-columns'
  ui:
    name: "#cake_name"
    description: "#cake_story"
    category: "#cake_category_id"
    tags: "#cake_tags"
    save_button: '#save-button'

  modelEvents:
    'invalid': 'displayError'

  events :
    "keyup input": "refreshStatus"
    "change select": "refreshStatus"
    "submit #edit-cake" : "update"
    "click .add-photo": "launchAddPhoto"

  constructor: (options) ->
    super(options)
    @collection = @model.photos()

  update : (e) ->
    e.preventDefault()
    e.stopPropagation()
    @disableSaveButton()
    @model.save(null,
      success: @savedSuccessfully
      error: @couldNotSave
    )

  onRender: ->
    @$("#cake_category_id").val(@model.category_id())
    @ui.tags.tagit({ availableTags: csx.Tags.pluck('name') })
    @disableSaveButton()

  savedSuccessfully: (cake) =>
    window.location.hash = "cakes/#{cake.id}"

  couldNotSave: (cake, xhr) =>
    @enableSaveButton()
    error = new csx.Views.ErrorView
      el: @$('form#edit-cake'),
      attributesWithErrors: $.parseJSON(xhr.responseText)
    error.render()

  refreshStatus: ->
    @enableSaveButton()
    @model.set('name', @ui.name.val())
    @model.set('story', @ui.description.val())
    @model.set('category_id', @ui.category.val())
    @model.set('tags', @ui.tags.val())
    @model.isValid()

  displayError: (model, error) ->
    @disableSaveButton()

  enableSaveButton: ->
    @ui.save_button.removeAttr('disabled')

  disableSaveButton: ->
    @ui.save_button.attr('disabled', 'disabled')

  serializeData: ->
    {
      cake: @model.toJSON(),
      categories: csx.Categories.toJSON(),
    }

  launchAddPhoto: ->
    @displayModal(new csx.Views.Photos.NewModalView(cake: @model))

  displayModal: (view) ->
    $("#modal").html(view.render().el)
    $("#modal").modal()