Simplify comments_index.js

This commit is contained in:
Micha Wrobel 2012-03-04 16:13:01 +01:00
parent ea62987c06
commit a2d1b1a15f
3 changed files with 37 additions and 35 deletions

View File

@ -1,14 +0,0 @@
<ul class="comments">
</ul>
{{#if show_form}}
<form id="new-comment">
<p>
<textarea type="text" name="body" id="comment-body"></textarea>
</p>
<input type="submit" value="Post">
</form>
{{else}}
<div>You need to sign in to create a comment.</div>
{{/if}}

View File

@ -1,28 +1,29 @@
class AsciiIo.Views.CommentsIndex extends AsciiIo.Views.Base class AsciiIo.Views.CommentsIndex extends AsciiIo.Views.Base
el: '#comments' el: '#comments'
template: JST['backbone/templates/comments/index']
events:
'submit #new-comment': 'createComment'
initialize: -> initialize: ->
@collection.on('reset', @render, this) @collection.on('reset', @addAll, this)
@collection.on('add', @render, this) @collection.on('add', @addOne, this)
render: -> $('#new-comment').submit (event)=>
$(@el).html @template( show_form: @current_user ) @createComment(event)
$comments = this.$('.comments')
addAll: ->
@collection.each (comment) => @collection.each (comment) =>
view = new AsciiIo.Views.CommentEntry({ model: comment, collection: @collection}) @addOne(comment)
$comments.append view.render().el
this
addOne:(comment) ->
view = new AsciiIo.Views.CommentEntry({ model: comment, collection: @collection})
$(this.el).append view.render().el
this this
createComment: (event) -> createComment: (event) ->
event.preventDefault() event.preventDefault()
attrs = body: $('#comment-body').val() attrs = body: $('#comment-body').val()
@collection.create attrs, @collection.create attrs,
wait: true wait: true

View File

@ -17,16 +17,31 @@
<h2>Comments</h2> <h2>Comments</h2>
<div id="comments"></div> <div class="comments-container">
<ul id="comments">
</ul>
<% if current_user %>
<form id="new-comment">
<p>
<textarea type="text" name="body" id="comment-body"></textarea>
</p>
<input type="submit" value="Post">
</form>
<% else %>
<div><%= link_to "Login in", login_path %> to create a comment.</div>
<% end %>
</div>
<script type="text/javascript"> <script type="text/javascript">
jQuery(document).ready( function(){ jQuery( function(){
var comments = new AsciiIo.Collections.Comments(); var comments = new AsciiIo.Collections.Comments();
var asciicast_id = <%= @asciicast.id %> var asciicast_id = <%= @asciicast.id %>
comments.url = ['/api/asciicasts/', asciicast_id, '/comments'].join(''); comments.url = ['/api/asciicasts/', asciicast_id, '/comments'].join('');
comments.fetch(); comments.fetch();
view = new AsciiIo.Views.CommentsIndex({ collection: comments }); new AsciiIo.Views.CommentsIndex({ collection: comments });
}) })
</script> </script>