node.js--闪出消息

来源:互联网 发布:广州网络优化 编辑:程序博客网 时间:2024/05/16 11:28


前面说了创建,显示,编辑,删除。现在说说闪出消息,比如创建完成了,显示创建成功,编辑之后显示修改成功,删除之后显示删除成功,总之要让用户知道自己的操作是成功还是失败
步骤:
1)将一下两行内容加到app.configure中去:
  app.use(express.cookieParser());//告诉ExpressParser启用cookieParser,用于保存回话。
  app.use(express.session({ secret: "OZhCLfxlGp9TtzSXmJtq" }));//给Express设置一个用于保护回话安全的密码。

2)在路由中设置提示信息:
app.get('/tasks', function(req, res){
  Task.find({}, function (err, docs) {
    res.render('tasks/index', {
      title: 'Tasks index view',
      docs: docs,
      flash: req.flash()
    });
  });
});

app.get('/tasks/new', function(req, res){
  res.render('tasks/new.jade', {
    title: 'New task view',
    flash: req.flash()
  });
});

app.post('/tasks', function(req, res){
  var task = new Task(req.body.task);
  task.save(function (err) {
    if (!err) {
      req.flash('info', 'Task created');
      res.redirect('/tasks');
    }
    else {
      req.flash('warning', err);
      res.redirect('/tasks/new');
    }
  });
});

app.get('/tasks/:id/edit', function(req, res){
  Task.findById(req.params.id, function (err, doc){
    res.render('tasks/edit', {
      title: 'Edit Task View',
      task: doc
    });
  });
});

app.put('/tasks/:id', function(req, res){
  Task.findById(req.params.id, function (err, doc){
    doc.updated_at = new Date();
    doc.task = req.body.task.task;
    doc.save(function(err) {
      if (!err){
        req.flash('info', 'Task updated');
        res.redirect('/tasks');
      }
      else {
        // error handling
      }
    });
  });
});

app.del('/tasks/:id', function(req, res){
  Task.findById(req.params.id, function (err, doc){
    if (!doc) return next(new NotFound('Document not found'));
    doc.remove(function() {
      req.flash('info', 'Task deleted');
      res.redirect('/tasks');
    });
  });
});


3)将闪出消息抽象成一个mixin:flash-messages.jade。

mixin flash-messages(flash)
  - if(flash.warning)
    div.alert-message.warning
      p= flash.warning
  - if(flash.info)
    div(data-alert='alert').alert-message.success
      p= flash.info


4)在显示层添加jade模板来检查消息是否存在,如果存在则显示出来。
h1 Your tasks
p
  a(href='/tasks/new', class='btn primary') Add a Task

-if(typeof flash != 'undefined')
  include ../mixins/flash-messages
  mixin flash-messages(flash)

- if(docs.length)
  table
    tr
      th Task
      th
      th
      each task in docs
        tr
          td #{task.task}
          td
            a.btn(href="/tasks/#{task.id}/edit") Edit
          td
            form(method='post', action='/tasks/' + task.id)
              input(name='_method', value='DELETE', type='hidden')
              button.btn(type='submit') Delete
- else
  p You don't have any tasks!

那么,增加,删除,显示成功的话,则会提示用户。




0 0
原创粉丝点击