post_submit.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. Template.postSubmit.onCreated(function () {
  2. Session.set('postSubmitErrors', {});
  3. });
  4. Template.postSubmit.helpers({
  5. errorMessage: function (field) {
  6. return Session.get('postSubmitErrors')[field];
  7. },
  8. errorClass: function (field) {
  9. return !!Session.get('postSubmitErrors')[field] ? 'has-error' : '';
  10. }
  11. });
  12. Template.postSubmit.events({
  13. 'submit form': function (e) {
  14. e.preventDefault();
  15. var post = {
  16. url: $(e.target).find('[name=url]').val(),
  17. title: $(e.target).find('[name=title]').val()
  18. };
  19. var errors = validatePost(post);
  20. if (errors.title || errors.url) {
  21. Session.set('postSubmitErrors', errors);
  22. // We return to abort the helper, not for anyone using the result.
  23. return;
  24. }
  25. Meteor.call('postInsert', post, function (error, result) {
  26. // Display the error to the user and abort.
  27. if (error) {
  28. return throwError(error.reason);
  29. }
  30. // Show this result but route anyway.
  31. if (result.postExists) {
  32. throwError("This link has already been posted");
  33. }
  34. Router.go('postPage', { _id: result._id });
  35. });
  36. }
  37. });