I'm working on my larger project to date, and on top of that I'm using underscore for the first time. All is working perfectly but I'd like some criticism on the use of underscore templating and underscore after function.
The goal of the app is to generate on the dom a messaging interface starting from an empty div. It gets initialized by passing the jQuery selector of that empty div.
I took out most of the code and left what I'd like to be reviewed the most, hope the flow of the app is quite clear anyway.
(function($) {
$(document).ready(function() {
var mssg_tmpl = {
msg_container : ' \
<div class="row-fluid msg-container well" id="msg-<% id %>"> \
some html \
</div>',
msg_reply : ' \
<div class="reply well message"> \
some html \
</div>'
};
mssg = {
init : function(selector) {
this.$container = $(selector);
this.tmpl = {}; // List of compiled templates functions
this.compileTemplates(mssg_tmpl);
this.messages = [{ // THIS IS HARDCODE TO ILLUSTRATE BASIC STRUCTURE
id: 1, // Thread opener
children: [2,3,4] // Replies
}, {
id: 5,
children: [6,7,8]
}];
for ( var i in this.messages) {
this.$container.append(this.tmpl.msg_container(this.messages[i])); // fn msg_container is a compiled template
this.messages[i].$container = $('#msg-' + this.messages[i].id);
this.fetchChildren(this.messages[i]);
}
this.bindEvents();
this.collapseMessages();
return this;
},
compileTemplates : function(templates) {
for ( var k in templates) {
this.tmpl[k] = _.template(templates[k]);
}
},
fetchChildren : function(message) {
var renderChildren = _.after(message.children.length, function() {
children = _.sortBy(children, 'id'); // Sort replies (oldest first)
for ( var i in children) {
message.$container.find('div.msg-reply-container').before(mssg.tmpl.msg_reply(children[i])); // fn msg_reply is a compiled template
}
});
var children = [];
for ( var i in message.children) {
$.ajax({
url : 'getmessage.htm?messageId=' + message.children[i]
}).done(function(response) {
children.push(response);
renderChildren();
});
}
},
};
mssg = mssg.init('#messaging');
});
})(jQuery);