Skip to content

Instantly share code, notes, and snippets.

@micho
Created August 1, 2013 21:47
Show Gist options
  • Save micho/6135657 to your computer and use it in GitHub Desktop.
Save micho/6135657 to your computer and use it in GitHub Desktop.
Votes.js, add a voting count to Teambox
/**
* Adds a Like button to tasks, so users can like them.
*
* By default there are no votes enabled in the project. To enable:
*
* project.metadata('apps').set({ votes: true });
* project.metadata('apps').save();
*
*/
(function () {
function addVoteCounter(view) {
var task = view.model, voted_by, $vote;
// If this project doesn't have votes enabled, skip
if (!task.rel('project').metadata('apps').get('votes')) {
return;
}
voted_by = task.metadata('votes').get('voted_by') || [];
// Insert vote element
$vote = $("<div class='js-vote vote_counter'><span class='icon-thumbs-up'></span></div>");
$vote.append($("<span class='js-vote-count'>").text(voted_by.length));
if (voted_by.indexOf(Teambox.models.user.id) !== -1) {
$vote.addClass('voted');
}
$(view.el).find(".taskHeader .comment_count").before($vote);
// Prepare click action
$vote.unbind().click(function (evt) {
evt.stopPropagation();
// If not voted, vote. If voted, unvote
if (voted_by.indexOf(Teambox.models.user.id) === -1) {
voted_by = _(voted_by.concat(Teambox.models.user.id)).uniq();
} else {
voted_by = _(voted_by).chain().reject(function (id) {
return id === Teambox.models.user.id;
}).uniq().value();
}
// Persist
task.metadata('votes').set({ 'voted_by': voted_by });
task.metadata('votes').save();
// Re-render
view.renderHeader();
});
}
$(function () {
Teambox.Events.bind('sdk:task:render', addVoteCounter);
Teambox.Events.bind('sdk:task:render:header', addVoteCounter);
$.injectCss(".vote_counter { display: inline-block; position: relative; top: -2px; font-size: 11px; }");
$.injectCss(".vote_counter span.icon-thumbs-up { font-size: 16px; }");
$.injectCss(".vote_counter:hover { color: black; }");
$.injectCss(".vote_counter.voted { color: #333; }");
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment