2014-01-18 3 views
1

프리앰블 : 이 질문을하는 가장 좋은 방법은 확실하지 않습니다. 제가 생각하는 것보다 더 일반적이라고 확신하고 있습니다. 내 관심사를 다루는 글로벌 패턴.locomotivej와 몽구스 : 컨트롤러에 약속 변수를 전달하십시오.

현재 제가 작업하고있는 원본 코드의 맥락에서 문제가 있습니다.

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 객체에 결과를 반환하는 방법을 생각할 수는 없으며 약속의 콜백에 대해 이야기하고 있습니다. 결과 변수를 반환하거나이 컨텍스트에서 contact_controller 객체를 노출하는 더 좋은 방법이 있습니까?

답변

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 
+0

정확히 내가 원하는 단순함입니다. 고맙습니다. –

+1

robertklep, 방금이 질문으로 돌아와서 고맙다고 말하고 싶습니다. 지난 몇 개월 동안이 패턴이 매우 유용하다는 것을 알게되었습니다. –

관련 문제