From a71c8253e22037821df284171ddc7900512b7ae6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Fri, 3 Apr 2015 10:04:05 +0200 Subject: [PATCH] Code cleanup, add Model._runWhenAttachedToApp --- common/models/user.js | 18 +++++++--------- lib/model.js | 49 ++++++++++++++++++------------------------- 2 files changed, 28 insertions(+), 39 deletions(-) diff --git a/common/models/user.js b/common/models/user.js index 94136a33..17c2628d 100644 --- a/common/models/user.js +++ b/common/models/user.js @@ -625,17 +625,15 @@ module.exports = function(User) { } ); - UserModel.on('attached', function() { - UserModel.afterRemote('confirm', function(ctx, inst, next) { - if (ctx.args.redirect !== undefined) { - if (!ctx.res) { - return next(new Error('The transport does not support HTTP redirects.')); - } - ctx.res.location(ctx.args.redirect); - ctx.res.status(302); + UserModel.afterRemote('confirm', function(ctx, inst, next) { + if (ctx.args.redirect !== undefined) { + if (!ctx.res) { + return next(new Error('The transport does not support HTTP redirects.')); } - next(); - }); + ctx.res.location(ctx.args.redirect); + ctx.res.status(302); + } + next(); }); // default models diff --git a/lib/model.js b/lib/model.js index 39b8428d..cc9146a8 100644 --- a/lib/model.js +++ b/lib/model.js @@ -180,36 +180,32 @@ module.exports = function(registry) { // before remote hook ModelCtor.beforeRemote = function(name, fn) { - var self = this; - if (this.app) { - var remotes = this.app.remotes(); - var className = self.modelName; + var className = this.modelName; + this._runWhenAttachedToApp(function(app) { + var remotes = app.remotes(); remotes.before(className + '.' + name, function(ctx, next) { fn(ctx, ctx.result, next); }); - } else { - var args = arguments; - this.once('attached', function() { - self.beforeRemote.apply(self, args); - }); - } + }); }; // after remote hook ModelCtor.afterRemote = function(name, fn) { - var self = this; - if (this.app) { - var remotes = this.app.remotes(); - var className = self.modelName; + var className = this.modelName; + this._runWhenAttachedToApp(function(app) { + var remotes = app.remotes(); remotes.after(className + '.' + name, function(ctx, next) { fn(ctx, ctx.result, next); }); - } else { - var args = arguments; - this.once('attached', function() { - self.afterRemote.apply(self, args); - }); - } + }); + }; + + ModelCtor._runWhenAttachedToApp = function(fn) { + if (this.app) return fn(this.app); + var self = this; + self.once('attached', function() { + fn(self.app); + }); }; // resolve relation functions @@ -375,15 +371,10 @@ module.exports = function(registry) { */ Model.getApp = function(callback) { - var Model = this; - if (this.app) { - callback(null, this.app); - } else { - Model.once('attached', function() { - assert(Model.app); - callback(null, Model.app); - }); - } + this._runWhenAttachedToApp(function(app) { + assert(Model.app); + callback(null, Model.app); + }); }; /**