locomotivejs和mongoose:将promise变量传递给控制器

时间:2014-01-18 04:25:40

标签: node.js express mongoose locomotivejs

前同步码: 我不确定这是否是提出这个问题的最佳方式,因为我相信它比我做的更为通用,并且可能有一个全球模式可以解决我的问题。

目前,这是我正在使用的原始代码上下文中的问题。

给定一个locomotivejs控制器,我们称之为Contact_Controller,其结构如下:

'\controllers\contact_controller.js
var locomotive = require('locomotive')
    , Controller = locomotive.Controller
    , Contact = require('../models/contact')
    , sender = require('../helpers/sender')
    ;


var Contact_Controller = new Controller();

然后:

Contact_Controller.list = function() {
//Provides a list of all current (successful) contact attempts


var controller = this;

Contact.find({status: 1}, function(err, results) {
    if(err) {
        controller.redirect(controller.urlFor({controller: "dashboard", action: "error"}));
    }
    controller.contacts = results;
    controller.render();
});
};

和模型:

'/models/contact.js
var mongoose = require('mongoose')
, mongooseTypes = require('mongoose-types')
, pass = require('pwd')
, crypto = require('crypto')
, Schema = mongoose.Schema
, Email = mongoose.SchemaTypes.Email;


var ContactSchema = new Schema({
email: {type: Email, required: true},
subject: {type: String, required: true },
message: { type: String, required: true},
status: {type: Number, required: true, default: 1},
contact_time: {type: Date, default: Date.now}
});


module.exports = mongoose.model('contact', ContactSchema);

在contact_controller的list动作中,我真的不想使用controller = this;我通常更喜欢使用redirect = this.redirect.bind(this);样式的本地化绑定来处理这些情况。

但是,我想不出一种方法可以将结果返回给控制器的this对象而不创建this的全局变量版本,并让promise的回调与之对话。有没有更好的方法来返回结果变量或在此上下文中公开contact_controller对象?

1 个答案:

答案 0 :(得分:4)

你是说这个吗?

Contact.find({status: 1}, function(err, results) {
  if (err) {
    this.redirect(this.urlFor({this: "dashboard", action: "error"}));
    return; // you should return here, otherwise `render` will still be called!
  }
  this.contacts = results;
  this.render();
}.bind(this));
 ^^^^^^^^^^^ here you bind the controller object to the callback function