Skip to content

Instantly share code, notes, and snippets.

@sixolet
Created March 28, 2013 23:21
Show Gist options
  • Save sixolet/5267615 to your computer and use it in GitHub Desktop.
Save sixolet/5267615 to your computer and use it in GitHub Desktop.
<head>
<title>questions</title>
</head>
<body>
{{loginButtons}}
<div class="container-fluid">
{{> questions}}
</div>
</body>
<template name="questions">
{{#if userId}}
<h1>Ask a question</h1>
<form class="form-compact">
<input type="text" id="questionText"></input>
<input type="button" id="questionAsk" class="btn" value="Ask"></input>
</form>
{{/if}}
{{#each allQuestions}}
<h3>
{{idx}}
{{question}}
{{score}}
{{#if showArrow}}
<a class="vote">&uarr;</a>
{{/if}}
</h3>
<p>{{email}}</p>
{{/each}}
</template>
//This is deliberately a global
Questions = new Meteor.Collection('Questions');
var getCurrentEmail = function () {
return Meteor.user() &&
Meteor.user().emails &&
Meteor.user().emails[0].address;
};
if (Meteor.isClient) {
Template.questions.allQuestions = function () {
var i = 0;
return _.map(Questions.find({}, {
sort: {score: -1}
}).fetch(), function (value) {
return _.extend(value, {idx: i++});
});
};
Template.questions.userId = function () {
return Meteor.userId();
},
Template.questions.showArrow = function () {
return Meteor.userId() &&
! _.contains(this.votes, Meteor.userId());
},
Template.questions.events({
"click #questionAsk": function (evt, templ) {
var question = templ.find("#questionText").value;
Questions.insert({
question: question,
score: 1,
email: getCurrentEmail(),
votes: [Meteor.userId()]
});
},
"click .vote": function (evt, templ) {
Questions.update(this._id, {
$inc: {score: 1},
$addToSet: {votes: Meteor.userId()}
});
}
});
}
if (Meteor.isServer) {
Questions.allow({
insert: function (userId, doc) {
if (! _.isEqual(doc.votes, [userId])) {
return false;
}
if (!doc.email || !doc.question) {
return false;
}
if (doc.score !== 1) {
return false;
}
return true;
},
update: function (userId, doc, fieldNames, modifier) {
return _.isEqual(modifier, {
$inc: {score: 1},
$addToSet: {votes: Meteor.userId()}
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment