is it possible to use dojo aspect on a method with no target?

时光总嘲笑我的痴心妄想 提交于 2019-12-12 01:46:08

问题


i have a module as follows:

define([...], function(...){
  function anothermethod() {...}
  function request() {....}
  request.anothermethod = anothermethod;
  return request;
}

Now i want to use dojo aspect before on the anothermethod method of the request method (closure). is it possible? If so, what should i put in the target parameter?

aspect.before(target, methodName, advisingFunction);

And the anothermethod is not called directly. First the request method is called which calls the anothermethod indirectly:

require(['dojo/aspect'], function(aspect){
  function anothermethod() {
    console.log('another method');
  }
  function beforeanothermethod() {
    console.log('before another method');
  }
  function request() {
    anothermethod();
  }
  request.anothermethod = anothermethod;
  aspect.before(request, 'anothermethod', beforeanothermethod);
  request();
})

https://jsfiddle.net/ahwgw5tb/1/


回答1:


You can use request as target. See:

require(['dojo/aspect'], function(aspect){
  function anothermethod() {
    console.log('another method');
  }
  function beforeanothermethod() {
    console.log('before another method');
  }
  
  function request() {}
  request.anothermethod = anothermethod;
  
  aspect.before(request, 'anothermethod', beforeanothermethod)
  
  request.anothermethod();
})
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>



回答2:


In your case, you already have a target, being request:

aspect.before(request, 'anothermethod', function() {
  // Do something
});

But to answer your original question, no you can't. You always need a target. The target in case of a normal function, would be the local scope where that function lives in, but there's no way to access that.

So, the best solution is to add it to a specific object (request) like you did.



来源:https://stackoverflow.com/questions/31281529/is-it-possible-to-use-dojo-aspect-on-a-method-with-no-target

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!