0
我想在幾個視圖中提供一個類別列表:將它們可視化爲一個列表,將它們作爲選項加載到創建產品表單中...爲了重用這些類別,我有將DAO從控制器中分離出來。問題是如何將返回的類別categoryDao
傳遞到categoryController
。從控制器中分離DAO以實現可重用性
這是我的MVC有文化的代碼我的問題:
// categoryDao.js
var Category = mongoose.model('Category');
exports.allCategories = function() {
Category.find().exec(function(err, categories) {
console.log(categories); // is properly defined
// I don't want to render categories like:
res.render('categories', {allCategories : categories});
// insted, I want to return them from within this callback and make them available in the categoryController.js. But you know
return categories; // is not quite right
}
// and of course
console.log(categories); // is undefined
}
// categoryController.js
var categoryDao = require ('./categoryDao.js');
exports.all = function(req, res) {
// make allCategories available in a list view
res.render('categories', {allCategories : categoryDao.allCategories});
}
// productController.js
var categoryDao = require ('./categoryDao.js');
exports.createForm = function(req, res) {
// make allCategories available in a select element in the create product form
res.render('create', {allCategories : categoryDao.allCategories});
}
// categoryRoutes.js
var categoryController = require ('./categoryController.js');
app.route('/categories').get(categoryController.all);
在實際的使用情況中,我們想渲染除類別之外的其他東西。例如,爲了給'editForm'一個產品,我們可以'res.render'產品信息來編輯除了可以選擇的類別。所以我們必須從'editForm'中調用'productDao'。我們如何做到這一點? – arymeo 2014-09-12 14:26:33
@arymeo這是最好的一個新問題。 – JohnnyHK 2014-09-12 14:47:18
好的,謝謝@JohnnyHK – arymeo 2014-09-12 15:11:29