javascriptfunctionaopmethod-modifiercujojs

Can i add method after method being executed meld aop


Consider I have class

 function home {}{
   this.door=function(){},
   this.tiles=function(){}
 }

I have to add some message after it's methods are called using this library called meld js (https://github.com/cujojs/meld/blob/master/docs/api.md#meldafter)

my try

var allMethods = new home();

   Object.keys(allMethods).forEach(function(k){

       aop.after(Object.prototype,key,function(){
            console.log('Dont use me i am old')
       });
  })

is this a right approach ?


Solution

  • Your approach is correct but you have several errors in your code. First, the home function should have () instead of {}:

    function home() {
        this.door=function(){},
        this.tiles=function(){}
    }
    

    Second, in your AOP code you need to provide the object to the after() method and not the prototype.

    var allMethods = new home();
    Object.keys(allMethods).forEach(function(k){
        aop.after(allMethods,k,function(){
            console.log('Dont use me i am old')
        });
    })
    

    (Also you need to use variable k and not key since that's the one defined in the forEach method)

    If you'll run one of the methods you'll get the wished output.

    allMethods.door() // result 'Dont use me i am old'