2015-04-23 13:33:29 -04:00
|
|
|
import PostView from "discourse/views/post";
|
|
|
|
|
|
|
|
function createPollView(container, post, poll, vote) {
|
|
|
|
const controller = container.lookup("controller:poll", { singleton: false }),
|
|
|
|
view = container.lookup("view:poll");
|
|
|
|
|
|
|
|
controller.set("vote", vote);
|
|
|
|
|
|
|
|
controller.setProperties({
|
|
|
|
model: Em.Object.create(poll),
|
|
|
|
post: post,
|
|
|
|
});
|
|
|
|
|
|
|
|
view.set("controller", controller);
|
|
|
|
|
|
|
|
return view;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default {
|
|
|
|
name: "extend-for-poll",
|
|
|
|
|
|
|
|
initialize(container) {
|
|
|
|
|
2015-04-27 12:59:29 -04:00
|
|
|
const messageBus = container.lookup("message-bus:main");
|
|
|
|
|
|
|
|
// listen for back-end to tell us when a post has a poll
|
|
|
|
messageBus.subscribe("/polls", data => {
|
|
|
|
const post = container.lookup("controller:topic").get("postStream").findLoadedPost(data.post_id);
|
|
|
|
// HACK to trigger the "postViewUpdated" event
|
|
|
|
post.set("cooked", post.get("cooked") + " ");
|
|
|
|
});
|
|
|
|
|
2015-04-23 13:33:29 -04:00
|
|
|
// overwrite polls
|
|
|
|
PostView.reopen({
|
|
|
|
_createPollViews: function($post) {
|
|
|
|
const self = this,
|
|
|
|
post = this.get("post"),
|
|
|
|
polls = post.get("polls"),
|
|
|
|
votes = post.get("polls_votes") || {};
|
|
|
|
|
|
|
|
// don't even bother when there's no poll
|
|
|
|
if (!polls) { return; }
|
|
|
|
|
2015-04-25 18:12:19 -04:00
|
|
|
// clean-up if needed
|
|
|
|
this._cleanUpPollViews();
|
|
|
|
|
2015-04-23 13:33:29 -04:00
|
|
|
const pollViews = {};
|
|
|
|
|
|
|
|
// iterate over all polls
|
|
|
|
$(".poll", $post).each(function() {
|
|
|
|
const $div = $("<div>"),
|
|
|
|
$poll = $(this),
|
|
|
|
pollName = $poll.data("poll-name"),
|
|
|
|
pollView = createPollView(container, post, polls[pollName], votes[pollName]);
|
|
|
|
|
|
|
|
$poll.replaceWith($div);
|
|
|
|
pollView.constructor.renderer.replaceIn(pollView, $div[0]);
|
|
|
|
pollViews[pollName] = pollView;
|
|
|
|
});
|
|
|
|
|
|
|
|
this.messageBus.subscribe("/polls/" + this.get("post.id"), results => {
|
2015-04-25 18:12:19 -04:00
|
|
|
if (results && results.polls) {
|
|
|
|
_.forEach(results.polls, poll => {
|
|
|
|
if (pollViews[poll.name]) {
|
|
|
|
pollViews[poll.name].get("controller").set("model", Em.Object.create(poll));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2015-04-23 13:33:29 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
this.set("pollViews", pollViews);
|
2015-04-25 18:12:19 -04:00
|
|
|
}.on("postViewInserted", "postViewUpdated"),
|
2015-04-23 13:33:29 -04:00
|
|
|
|
|
|
|
_cleanUpPollViews: function() {
|
2015-04-25 18:12:19 -04:00
|
|
|
this.messageBus.unsubscribe("/polls/" + this.get("post.id"));
|
2015-04-23 13:33:29 -04:00
|
|
|
|
|
|
|
if (this.get("pollViews")) {
|
|
|
|
_.forEach(this.get("pollViews"), v => v.destroy());
|
|
|
|
}
|
|
|
|
}.on("willClearRender")
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|