mplatts
11/20/2014 - 10:45 AM

Meteor Cheatsheet www.webtempest.com

Meteor Cheatsheet www.webtempest.com

Router.configure(
  layoutTemplate: 'layout'
  loadingTemplate: 'loading'
  notFoundTemplate: 'notFound'
)

#   ONLOGIN
if Meteor.isClient
  Tracker.autorun (tracker) ->
    if Meteor.user()
      Router.go('modulesList', {username: Meteor.user().username})
      tracker.stop()

#   CONTROLLERS ----------------------------------


class ModulesListController extends RouteController
  waitOn: ->
    [
      Meteor.subscribe 'modules', @params.username
      Meteor.subscribe 'user', @params.username
      Meteor.subscribe 'tagsList'
    ]

  data: ->
    {
      user: Meteor.users.findOne({username: @params.username})
    }

  action: -> @render()

#    ROUTES ----------------------------------

Router.route '/', {
  name: 'homePage'
  waitOn: ->
    Meteor.subscribe 'usersList'
}

Router.route '/teachers/:username', {
  name: 'modulesList'
  controller: ModulesListController
}

Router.route('/evidence/submit', {
  name: 'moduleSubmit'
  waitOn: -> Meteor.subscribe 'tagsList'
  data: -> {tags: Tags.find()}
})

Router.route 'tags', {
  waitOn: -> Meteor.subscribe 'tagsList'
  name: 'tags'
  data: -> {tags: Tags.find()}
}

requireLogin = ->
  if !Meteor.user()
    if Meteor.loggingIn()
      @render(@loadingTemplate)
    else
      @render('accessDenied')
  else
    @next()

Router.onBeforeAction(requireLogin, {only: 'moduleSubmit'})
Meteor.publish 'modules', (username) ->
  check(username, String)

  # TODO only if user has paid
  user = Meteor.users.findOne({username: username})
  if user && user._id
    Modules.find({userId: user._id})
  else
    []
Template.moduleSubmit.events({
  'submit form': (e) ->
    e.preventDefault()

    module = {
      title: $(e.target).find('[name=title]').val()
      body: $(e.target).find('#body').code()
      tags: $(e.target).find('select.chosen-select').val()
    }

    module.tags = [] unless module.tags?

    Meteor.call('moduleInsert', module, (error, result) ->
      # Display the error to the user and abort
      if error
        return alert(error.reason)

      if result.moduleExists
        alert('This title has already been posted: ' + result._id)

      Router.go('modulesList', {username: Meteor.user().username})
    )
})
@ownsDocument = (userId, doc) -> doc && doc.userId == userId
Package.describe({
  name: 'mplatts:chosen',
  summary: 'Wrapper for chosen.js by Harvest',
  version: '1.0.0'
});

Package.onUse(function(api) {
  api.use('jquery');
  files = [
    'chosen-sprite.png',
    'chosen-sprite@2x.png',
    'chosen.css',
    'chosen.jquery.js'
  ];
  api.addFiles(files, 'client');
});
Template.nav.helpers
  isActive: (name) ->
    routeName = Router.current().route.getName()
    if name == routeName
      "active"
    else
      ""
@Modules = new Mongo.Collection('modules')

Modules.allow
  update: (userId, module) -> ownsDocument(userId, module)
  remove: (userId, module) -> ownsDocument(userId, module)

Modules.deny
  update: (userId, module, fieldNames) -> _.without(fieldNames, 'body', 'title', 'tags').length > 0

Meteor.methods
  moduleInsert: (moduleAttributes) ->
    check(Meteor.userId(), String)
    check(moduleAttributes, {
      title: String
      body: String
      tags: Array
    })

    # Make sure there are no duplicate titles
    user = Meteor.user()
    moduleWithSameTitle = Modules.findOne({title: moduleAttributes.title, userId: user._id})
    if moduleWithSameTitle
      return {
        moduleExists: true
        _id: moduleWithSameTitle._id
      }

    # Find the latest position so we can put it on the bottom
    latestPosition = if Modules.find({userId: user._id}).count() == 0
      0
    else
      Modules.find({userId: user._id}, {sort: {position: -1}, limit: 1}).fetch()[0].position + 1

    # Add some extra attributes
    module = _.extend(moduleAttributes, {
      userId: user._id
      author: user.username
      submitted: new Date()
      position: latestPosition
    })

    # The actual insert
    moduleId = Modules.insert(module)

    # Return the id of the freshly minted module
    {_id: moduleId}

  moduleUpdatePosition: (moduleIds) ->
    check Meteor.userId(), String
    check moduleIds, Array
    
    totalCount = Modules.find({userId: Meteor.userId()}).count()
    if totalCount != moduleIds.length
      throw new Meteor.Error("bad-module-positions-update", "The number of moduleIds to update is different to the number of modules")

    _(moduleIds).each (moduleId, i) ->
      Modules.update({_id: moduleId}, $set: {position: i})

    moduleIds

Template.moduleItem.events(
  'click .edit': (e, tpl) ->
    e.preventDefault()
    Session.set('editing_module', @_id)
    makeEditable(tpl.$('.module-body'))

  'click .save': (e, tpl) ->
    e.preventDefault()
    attrs =
      title: $('input[name="title"]').val()
      tags: $('select[name="tags"]').val()
      body: tpl.$('.module-body').code()

    attrs.tags = [] unless attrs.tags?
    Modules.update({_id: @_id}, $set: attrs)
    tpl.$('.module-body').destroy()
    Session.set('editing_module', null)

  'click .delete': (e, tpl) ->
    e.preventDefault()
    if confirm("Delete?")
      currentModuleId = @_id
      Modules.remove(currentModuleId)
      Session.set('editing_module', null)

  'click .cancel': (e, tpl) ->
    e.preventDefault()
    tpl.$('.module-body').destroy()
    Session.set('editing_module', null)
)


Template.moduleEditing.rendered = ->
  @$('select[name="tags"]').chosen()
  makeEditable(@$('.module-body'))
Post.findOne() // returns obj
Post.findOne({_id: id, title: 'Hello world!'})
Post.find() // returns cursor - finds all posts
Post.find({title: "Hello World!"})