【问题标题】:locomotivejs and mongoose: passing promise variables to a controllerlocomotivejs 和 mongoose:将 promise 变量传递给控制器
【发布时间】:2014-01-18 14:09:29
【问题描述】:

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

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

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

【问题讨论】:

    标签: node.js express mongoose locomotivejs


    【解决方案1】:

    你是这个意思吗?

    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
    

    【讨论】:

    • 这正是我所希望的那种简单性。谢谢。
    • robertklep,我刚回到这个问题,我想说声谢谢。在过去的几个月里,我发现这种模式在我的编码中非常有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多