locomotivejs和mongoose:将promiseparameter passing给控制器

序言:我不确定这是不是问这个问题的最好方法,因为我相当肯定这个问题比我做得更笼统,可能有一个全球模式来解决我的问题。

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

给定一个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的列表动作中,我真的宁愿不使用controller = this; 我通常更喜欢使用redirect = this.redirect.bind(this); 风格的本地化的绑定来处理这种情况。

然而,我不能想到一种方法来返回结果的控制器的this对象,而不创build一个全球variables版本,并承诺的callback说话。 有没有更好的方法来返回结果variables或在这种情况下暴露contact_controller对象?

你的意思是?

 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