I'm currently using this pattern in my JavaScript code. Somewhere in my code I use Dnianas.Post.init
. init
fires and it will bind DOM events.
At first everything was OK. But then, when you look at likePost
method you will see that, I'm not using the var
keyword to declare my variables. Because I if do that, then it won't be available to renderCreatedPost
method. So basically I'm forced to do that.
I'm trying to adapt a new pattern and refactor my code that allow for that.
As you may know, defining variables without the var
keyword is a bad practice and will result in errors in strict mode
.
Dnianas.Post = {
init: function () {
this.bindEvents();
},
bindEvents: function () {
$(document).on('submit', '#postForm', this.createPost);
$(document).on('click', '#likePost', this.likePost);
},
createPost: function (event) {
var self = Dnianas.Post;
var request = $.ajax({
url: '/posts/create',
data: $(this).serialize(),
beforeSend: function () {
$loading.show();
},
complete: function () {
$loading.hide();
}
});
request.done(function (data) {
self.renderCreatedPost(data);
});
event.preventDefault();
},
renderCreatedPost: function (data) {
if (data.success == 'false') {
$('.error').empty().append(data.message).slideDown(100).delay(3000).slideUp(250);
} else {
this.postForm[0].reset();
$(data.post_html).insertAfter(this.postForm).hide().delay(100).slideDown(400);
$('.no-posts').hide();
}
},
likePost: function () {
self = Dnianas.Post;
$likePostEl = $(this);
$postLikeCountEl = $likePostEl.children('#likeCount');
postLikeCount = $postLikeCountEl.data('count');
var request = $.ajax({
url: '/posts/like',
data: {
post_id: $likePostEl.parents().get(2).dataset.id,
user_id: $likePostEl.parents().get(2).dataset.userid,
like_count: postLikeCount,
_token: token
}
});
request.done(function (data) {
self.renderPostLike(data);
});
},
renderPostLike: function (data) {
if (data.like) {
$likePostEl.children('.likeIcon').addClass('liked');
$postLikeCountEl.addClass('liked');
} else {
$likePostEl.children('.likeIcon').removeClass('liked');
$postLikeCountEl.removeClass('liked');
}
$postLikeCountEl.text(data.like_count);
},
getMaxId: function($element) {
// Filter through the ids
var ids = $element.map(function () {
return +$(this).data('id') || 0;
});
// Get the highest id attribute
last_id = Math.max.apply(Math, ids);
// Return the maximum id.
return last_id;
},
getNewPosts: function () {
var self = Dnianas.Post;
var ids = [];
var $postEl = $('.poster_memb .tab_post');
last_id = 0;
// If there was posts.
if ($postEl.length > 0) {
self.getMaxId($postEl);
}
var request = $.ajax({
url: '/posts/latest/' + last_id,
type: 'GET',
dataType: 'JSON'
});
request.done(function (data) {
self.renderLatestPost(data);
});
},
renderLatestPost: function (data) {
if (data && data.is_new == 'true' && data.html) {
$('.no-posts').hide();
$(data.html).insertAfter('#postForm').hide().slideDown(500);
}
// Run the function every 10 seconds.
setTimeout(this.getNewPosts, 10000);
}
};