29

您使用哪个 Javascript AOP 库,它的主要功能是什么?

4

3 回答 3

30

这是我到目前为止发现的:

  • dotvoid的实现,简洁的语法,很好用,这篇文章很好地介绍了为什么/如何使用给定的代码,支持介绍,但是有问题,
  • Dojo 在dojox中似乎有一个很好的内置实现,这里有一个关于如何使用它的很好的介绍,
  • 有一个 jQuery 插件jquery-aop,语法更粗略,在 javascript 对象中传递对象和方法,
  • 具有更粗略语法的AspectJS(需要将切入点类型作为参数传递给单个方法)

就像我说的,dotvoid 的代码不起作用。我稍微纠正了一下,得到了一些似乎效果更好的东西:

InvalidAspect = new Error("Missing a valid aspect. Aspect is not a function.");
InvalidObject = new Error("Missing valid object or an array of valid objects.");
InvalidMethod = new Error("Missing valid method to apply aspect on.");

function doBefore(beforeFunc,func){
    return function(){
        beforeFunc.apply(this,arguments);
        return func.apply(this,arguments);
    };  
}

function doAfter(func, afterFunc){
    return function(){
        var res = func.apply(this,arguments);
        afterFunc.apply(this,arguments);
        return res;   
    };
}

Aspects = function(){};
Aspects.prototype={
    _addIntroduction : function(intro, obj){
         for (var m in intro.prototype) {
              obj.prototype[m] = intro.prototype[m];
            }
        },

    addIntroduction : function(aspect, objs){
        var oType = typeof(objs);

        if (typeof(aspect) != 'function')
        throw(InvalidAspect);

        if (oType == 'function'){
            this._addIntroduction(aspect, objs);
        }
        else if (oType == 'object'){
            for (var n = 0; n < objs.length; n++){
                this._addIntroduction(aspect, objs[n]);
            }
        }
        else{
            throw InvalidObject;
        }
    },

    addBefore : function(aspect, obj, funcs){
          var fType = typeof(funcs);

          if (typeof(aspect) != 'function')
            throw(InvalidAspect);

          if (fType != 'object')
            funcs = Array(funcs);

          for (var n = 0; n < funcs.length; n++){
            var fName = funcs[n];
            var old = obj.prototype[fName];

            if (!old)
              throw InvalidMethod;

            var res = doBefore(aspect,old)
            obj.prototype[fName] = res;
        }
    },

    addAfter : function(aspect, obj, funcs) {
          if (typeof(aspect) != 'function')
            throw InvalidAspect;

          if (typeof(funcs) != 'object')
            funcs = Array(funcs);

          for (var n = 0; n < funcs.length; n++)
          {
            var fName = funcs[n];
            var old = obj.prototype[fName];

            if (!old)
              throw InvalidMethod;

            var res = doAfter(old,aspect);
            obj.prototype[fName] = res;
          }
        },

    addAround : function(aspect, obj, funcs){
          if (typeof(aspect) != 'function')
            throw InvalidAspect;

          if (typeof(funcs) != 'object')
            funcs = Array(funcs);

          for (var n = 0; n < funcs.length; n++)
          {
            var fName = funcs[n];
            var old = obj.prototype[fName];
            if (!old)
              throw InvalidMethod;

            var res = aspect(old);
            obj.prototype[fName] = res;
          }

          return true;
        }
}
于 2009-06-17T08:00:10.917 回答
13

你见过meld.jsaop.js来自 https://github.com/cujojs吗?

SpringSource 在那里提供了 AOP 功能,此外还有许多其他对高级 Javascript 程序员有用的东西。

免责声明:我为 SpringSource 工作。

于 2013-01-30T21:19:12.330 回答
3

基于 dotvoid 解决方案,我为自己的项目需求创建了自己的 JS AOP 版本。我基本上想最小化方面设置成本,所以我在 Function.prototype 中添加了方面设置功能。

Function.prototype.applyBefore = function (aspect, targetFuncNames) {
....
}

我还需要支持 aync 回调,例如支持某些方法的身份验证和授权。例如:

var authenticateAspect = function (error, success, context, args) {
    logger.log('authenticate (applyBefore async) aspect is being called');
    var request = $.ajax({
        url: "http://localhost/BlogWeb/api/user/authenticate",
        type: "GET",
        data: { username:'jeff', pwd:'jeff' },
        success: function (data) {
            if (data) {
                success();
            } else {
                error();
            }
        },
        error: error
    });
    return request;
};

Person.applyBefore(authenticateAspect, 'sendNotification');

var p1 = new Person();

p1.sendNotification();

要实现这一点,我需要运行安全性并在成功时继续或在失败时停止执行。

var invalidAspect = new Error("Missing a valid aspect. Aspect is not a function."),
    invalidMethod = new Error("Missing valid method to apply aspect on.");

///Parameters: aspect - defines the methods we want call before or/and 
///             after each method call ob target obejct
///            targetFuncNames - target function names to apply aspects
///Return: it should return a new object with all aspects setup on target object
Function.prototype.applyBefore = function (aspect, targetFuncNames) {
    if (typeof (aspect) != 'function')
        throw invalidAspect;

    if (typeof (targetFuncNames) != 'object')
        targetFuncNames = Array(targetFuncNames);

    var targetObj = this;
    //error handling function

    // Copy the properties over onto the new prototype
    for (var i = 0, len = targetFuncNames.length; i < len; i++) {
        var funcName = targetFuncNames[i];
        var targetFunc = targetObj.prototype[funcName];

        if (!targetFunc)
            throw invalidMethod;


        targetObj.prototype[funcName] = function () {
            var self = this, args = arguments;
            var success = function() {
                return targetFunc.apply(self, args);
            };
            var error = function () {
                logger.log('applyBefore aspect failed to pass');
                //log the error and throw new error
                throw new Error('applyBefore aspect failed to pass');
            };

            var aspectResult = aspect.apply(null, Array.prototype.concat([error, success, self], args));
            return aspectResult;
        };
    }
};

完整的实现可以在http://www.jeffjin.net/aop-with-javascript

于 2013-04-21T04:20:23.830 回答