面向对象的JS(6) 自定义异常和事件

1 自定义异常
在JavaScript中有内置的异常比如Error,TypeError和SyntaxError,这些异常可以在运行时创建抛出。每个异常是未受查的。一个普通对象可以用在异常抛出语句中。因此我们可以创建自定义的异常,并可以抛出和捕捉。自定义异常一个比较好的做法是继承JavaScript的标准Error对象。
function BaseException() {}
BaseException.prototype = new Error();
BaseException.prototype.constructor = BaseException;
BaseException.prototype.toString = function () {
// note that name and message are properties of Error
return this.name + ": "+this.message;
};

function NegativeNumberException(value) {
this.name = "NegativeNumberException";
this.message = "Negative number!Value: "+value;
}
NegativeNumberException.prototype = new BaseException();
NegativeNumberException.prototype.constructor = NegativeNumberException;

function EmptyInputException() {
this.name = "EmptyInputException";
this.message = "Empty input!";
}
EmptyInputException.prototype = new BaseException();
EmptyInputException.prototype.constructor = EmptyInputException;
var InputValidator = (function () {
var InputValidator = {};
InputValidator.validate = function (data) {
var validations = [validateNotNegative, validateNotEmpty];
for (var i = 0; i < validations.length; i++) {
try {
validations[i](data);
} catch (e) {
if (e instanceof NegativeNumberException) {
//re-throw
throw e;
} else if (e instanceof EmptyInputException) {
// tolerate it
data = "0";
}
}
}
};
return InputValidator;

function validateNotNegative(data) {
if (data < 0)
throw new NegativeNumberException(data)
}
function validateNotEmpty(data) {
if (data == "" || data.trim() == "")
throw new EmptyInputException();
}
})();
try {
InputValidator.validate("-1");
} catch (e) {
console.log(e.toString()); // NegativeNumberException:Negative number!Value: -1
console.log("Validation is done."); // Validation is done.
var validations = [validateNotNegative, validateNotEmpty];
}

2 自定义事件
自定义事件可以减少代码的复杂性并降低对象之间的耦合性。下面是一个典型的事件模式:
function EventManager() {}
var listeners = {};
EventManager.fireEvent = function (eventName, eventProperties) {
if (!listeners[eventName])
return;
for (var i = 0; i < listeners[eventName].length; i++) {
listeners[eventName][i](eventProperties);
}
};
EventManager.addListener = function (eventName, callback) {
if (!listeners[eventName])
listeners[eventName] = [];
listeners[eventName].push(callback);
};
EventManager.removeListener = function (eventName, callback) {
if (!listeners[eventName])
return;
for (var i = 0; i < listeners[eventName].length; i++) {
if (listeners[eventName][i] == callback) {
delete listeners[eventName][i];
return;
}
}
};
EventManager.addListener("popupSelected", function (props) {
console.log("Invoked popupSelected event: "+props.itemID);
});
EventManager.fireEvent("popupSelected", {
itemID: "100"
}); //

Invoked popupSelected event: 100
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值