Skip to content

Instantly share code, notes, and snippets.

@minipai
Last active December 19, 2015 13:29
Show Gist options
  • Save minipai/5962789 to your computer and use it in GitHub Desktop.
Save minipai/5962789 to your computer and use it in GitHub Desktop.
Refactor from Backbone to Angular.
window.commentsCtrl = ($http, $scope, $element)->
update = ()->
$http.get(location.pathname).success (result)->
$scope.comments = result.comments
update()
e$form = $element.find('form')
e$form.submit (e)->
e.preventDefault()
$.post(e$form.attr('action'), e$form.serialize(), ()->
update()
e$form.find('textarea').val()
)
App.CommentModel = Backbone.Model.extend({
url: '/comments'
})
App.CommentCollection = Backbone.Collection.extend({
model: App.CommentModel
url: '/comments'
})
App.CommentItem = Backbone.View.extend({
render: ()->
html = JST['comments/show']( @model.toJSON() )
this.$el.empty().append( html )
return this
})
App.CommentList = Backbone.View.extend({
tagName: 'table'
className: 'table'
initialize: ()->
@collection.on('all', ( ()-> console.log(arguments) ) , @)
@collection.on('sync', @render, @)
@collection.on('add', @renderItem, @)
@collection.fetch({data: {post_id: @options.postId}})
render: ()->
self = this
this.$el.empty()
@collection.each (comment)->
self.renderItem(comment)
return this
renderItem: (comment)->
view = new App.CommentItem( {model: comment} )
this.$el.append( view.render().$el.html() )
return this
})
$ ()->
comments = new App.CommentCollection()
commentsView = new App.CommentList({collection: comments, postId: data.postId})
$('.comments').append(commentsView.render().el)
$('.new-comment').on 'click', 'a', (e)->
e.preventDefault()
$(e.delegateTarget).load(e.target.href)
$('.new-comment').on 'submit', '#new_comment', (e)->
e.preventDefault()
$form = $(this)
createComment = $.ajax({
url : $form.attr('action')
type : 'POST'
data : $form.serializeArray()
dataType : 'json'
})
createComment.success (data, result)->
if result is not 'success'
return
comments.add(data)
$form.find('textarea').val('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment