Chcę nauczyć się pisać obiektowo w JavaScript i w tym celu zacząłem refraktoryzować swój projekt.
Zbudowałem taką strukturę
$(document).ready(function () {
HomeController.init('#single-post-container')
});
var HomeController = function (postService) {
var init = function (container) {
$(container).on('click', '.js-remove-post', removePost)
$(container).on('submit', '#add-new-comment-form', submitAddNewCommentForm)
//...
};
var submitAddNewCommentForm = function (e) {
currentActionPostId = $(e.currentTarget).data('post-id');
var targetFormId = 'form#' + e.currentTarget.id;
postService.addNewComment(targetFormId, addNewCommentSuccess, fail);
};
var addNewCommentSuccess = function (response) {
appendCommentsToPost(response.responseText);
var commentsPageIndex = 1;
saveCommentsPageIndexInSession(commentsPageIndex);
manageCommentNavigationButtons(commentsPageIndex, response.responseText);
};
var removePost = function (e) {
//odzywam się do postService i usuwam post
};
return {
init: init
}
}(PostService);
var PostService = function () {
var addNewComment = function (targetFormId, addNewCommentSuccess, fail) {
$.ajax({
type: 'POST',
url: '/Home/AddNewComment',
dataType: 'html',
data: $(targetFormId).serialize(),
complete: function (response) {
addNewCommentSuccess(response)
},
error: function () {
fail()
}
});
};
return {
removePost: removePost,
addNewComment: addNewComment,
//...
}
}();
Przyjąłem taką konwencje jak widać powyżej ale mam wątpliwości czy dobrze ogarniam obsłużenie wysłania formularza (ajaxComplete). Bo w moim odczuciu wygląda to średnio. Czy da się to zrobić jakoś lepiej ?
Generalnie jak widać nie używam już eventów w HTML tylko robię to w js. Mam mieszane co do tego uczucia ale z tego co przeczytałem to best practice jest żeby html pozostał czysty.