面向对象的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

你可能感兴趣的:(自定义异常)