discourse/plugins/poll/assets/javascripts/initializers/poll.js.es6

103 lines
2.6 KiB
Plaintext
Raw Normal View History

import PollController from "discourse/plugins/poll/controllers/poll";
2014-02-04 21:53:09 -05:00
var Poll = Discourse.Model.extend({
post: null,
options: [],
closed: false,
2014-02-04 21:53:09 -05:00
postObserver: function() {
this.updateFromJson(this.get('post.poll_details'));
2014-02-04 21:53:09 -05:00
}.observes('post.poll_details'),
fetchNewPostDetails: Discourse.debounce(function() {
var self = this;
Discourse.debounce(function() {
self.get('post.topic.postStream').triggerChangedPost(self.get('post.id'), self.get('post.topic.updated_at'));
}, 500);
}).observes('post.topic.title'),
2014-04-10 23:35:07 -04:00
updateFromJson: function(json) {
2014-02-04 21:53:09 -05:00
var selectedOption = json["selected"];
var options = [];
Object.keys(json["options"]).forEach(function(option) {
options.push(Ember.Object.create({
option: option,
votes: json["options"][option],
checked: (option === selectedOption)
2014-02-04 21:53:09 -05:00
}));
});
this.set('options', options);
this.set('closed', json.closed);
2014-02-04 21:53:09 -05:00
},
saveVote: function(option) {
this.get('options').forEach(function(opt) {
opt.set('checked', opt.get('option') === option);
2014-02-04 21:53:09 -05:00
});
return Discourse.ajax("/poll", {
type: "PUT",
data: {post_id: this.get('post.id'), option: option}
}).then(function(newJSON) {
this.updateFromJson(newJSON);
2014-02-04 21:53:09 -05:00
}.bind(this));
}
});
var PollView = Ember.View.extend({
templateName: "poll",
classNames: ['poll-ui'],
});
function initializePollView(self) {
var post = self.get('post');
var pollDetails = post.get('poll_details');
var poll = Poll.create({post: post});
poll.updateFromJson(pollDetails);
2014-02-04 21:53:09 -05:00
var pollController = PollController.create({
poll: poll,
showResults: pollDetails["selected"],
postController: self.get('controller')
});
2014-12-04 08:48:25 -05:00
return self.createChildView(PollView, { controller: pollController });
2014-02-04 21:53:09 -05:00
}
export default {
name: 'poll',
2014-02-04 21:53:09 -05:00
initialize: function() {
Discourse.PostView.reopen({
createPollUI: function($post) {
var post = this.get('post');
if (!post.get('poll_details')) {
return;
}
var view = initializePollView(this);
var pollContainer = $post.find(".poll-ui:first");
if (pollContainer.length === 0) {
pollContainer = $post.find("ul:first");
}
2014-02-04 21:53:09 -05:00
2014-12-04 08:48:25 -05:00
var $div = $('<div>');
pollContainer.replaceWith($div);
view.constructor.renderer.appendTo(view, $div[0]);
this.set('pollView', view);
}.on('postViewInserted'),
clearPollView: function() {
if (this.get('pollView')) {
this.get('pollView').destroy();
}
}.on('willClearRender')
});
}
2014-12-04 08:48:25 -05:00
};