这个场景中我们将讲解两个控制器对象,一个用来处理网页的登录form(表单),另一个实际处理服务器的认证(通信)
根据典型的类的设计模式,我们在一个叫做Controller的类中将任务分解为基本功能,之后我们会衍生出两个子类,LoginController和AuthController,它们都继承自Controller而且特化某些基本行为。
// 父类
function Controller() {
this.errors = [];
}
Controller.prototype.showDialog = function(title,msg) {
// 在对话框中给用户显示标题和消息
};
Controller.prototype.success = function(msg) {
this.showDialog( "Success", msg );
};
Controller.prototype.failure = function(err) {
this.errors.push( err );
this.showDialog( "Error", err );
};
// 子类
function LoginController() {
Controller.call( this );
}
// 将子类链接到父类
LoginController.prototype = Object.create( Controller.prototype );
LoginController.prototype.getUser = function() {
return document.getElementById( "login_username" ).value;
};
LoginController.prototype.getPassword = function() {
return document.getElementById( "login_password" ).value;
};
LoginController.prototype.validateEntry = function(user,pw) {
user = user || this.getUser();
pw = pw || this.getPassword();
if (!(user && pw)) {
return this.failure( "Please enter a username & password!" );
}
else if (pw.length < 5) {
return this.failure( "Password must be 5+ characters!" );
}
// 到这里了?输入合法!
return true;
};
// 覆盖来扩展基本的failure()
LoginController.prototype.failure = function(err) {
// "super"调用
Controller.prototype.failure.call( this, "Login invalid: " + err );
};
// 子类
function AuthController(login) {
Controller.call( this );
// 除了继承外,我们还需要合成
this.login = login;
}
// 将子类链接到父类
AuthController.prototype = Object.create( Controller.prototype );
AuthController.prototype.server = function(url,data) {
return $.ajax( {
url: url,
data: data
} );
};
AuthController.prototype.checkAuth = function() {
var user = this.login.getUser();
var pw = this.login.getPassword();
if (this.login.validateEntry( user, pw )) {
this.server( "/check-auth",{
user: user,
pw: pw
} )
.then( this.success.bind( this ) )
.fail( this.failure.bind( this ) );
}
};
// 覆盖以扩展基本的success()
AuthController.prototype.success = function() {
// "super"调用
Controller.prototype.success.call( this, "Authenticated!" );
};
// 覆盖以扩展基本的failure()
AuthController.prototype.failure = function(err) {
// "super"调用
Controller.prototype.failure.call( this, "Auth Failed: " + err );
};