Skip to content

Commit 58c9df7

Browse files
committed
Introduce CommentView.appendTo()
To be able to scroll to the active comment we need to know when a comment is added to the DOM. Since we have more than one case and we don't want to repeat ourselves, we inverted the responsibility and now the `appendTo()` method takes care of adding a comment to the DOM and also scrolls down if needed.
1 parent 6a35c02 commit 58c9df7

1 file changed

Lines changed: 12 additions & 12 deletions

File tree

code_comments/htdocs/code-comments.js

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,22 @@
4646
template: _.template(CodeComments.templates.comment),
4747
initialize: function() {
4848
this.model.bind('change', this.render, this);
49+
this.is_active = this.model.id == CodeComments.active_comment_id;
4950
},
5051
render: function() {
5152
$(this.el).html(this.template(_.extend(this.model.toJSON(), {
5253
delete_url: CodeComments.delete_url,
53-
active: this.model.id == CodeComments.active_comment_id,
54+
active: this.is_active,
5455
can_delete: CodeComments.is_admin
5556
})));
5657
return this;
58+
},
59+
appendTo: function($el) {
60+
$el.append( this.render().el );
61+
if ( this.is_active ) {
62+
var comment_offset = $(this.el).offset();
63+
window.scrollTo( comment_offset.left, comment_offset.top );
64+
}
5765
}
5866
});
5967

@@ -79,7 +87,7 @@
7987

8088
addOne: function(comment) {
8189
var view = new CommentView({model: comment});
82-
this.$("ul.comments").append(view.render().el);
90+
view.appendTo( $( "ul.comments" ) );
8391
},
8492
addAll: function() {
8593
var view = this;
@@ -101,15 +109,7 @@
101109
this.viewPerLine = {};
102110
},
103111
render: function() {
104-
LineComments.fetchComments( 'line' ).complete( function() {
105-
window.setTimeout( function() {
106-
var anchor_id = '#comment-' + CodeComments.active_comment_id;
107-
if ( '' != anchor_id && $( anchor_id ).offset() ) {
108-
var new_position = $( anchor_id ).offset();
109-
window.scrollTo( new_position.left, new_position.top );
110-
}
111-
}, 30 ); // slight pause allows DOM updates to complete
112-
} );
112+
LineComments.fetchComments( 'line' );
113113
},
114114
addOne: function(comment) {
115115
var line = comment.get('line');
@@ -149,7 +149,7 @@
149149
addOne: function(comment) {
150150
var view = new CommentView({model: comment});
151151
this.line = comment.get('line');
152-
this.$("ul.comments").append(view.render().el);
152+
view.appendTo( $( "ul.comments" ) );
153153
},
154154
showAddCommentDialog: function() {
155155
var $parentRow = $( this.el ).prev()[0],

0 commit comments

Comments
 (0)