1

序言:我不确定这是否是提出这个问题的最佳方式,因为我相当确定它比我提出的更笼统,并且可能有一个全球模式可以解决我的担忧。

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

给定一个 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但是,如果不创建全局变量版本this并让 Promise 的回调与之对话,我想不出一种方法来将结果返回给控制器的对象。有没有更好的方法来返回结果变量或在此上下文中公开 contact_controller 对象?

4

1 回答 1

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
于 2014-01-18T06:09:29.923 回答