我想为脚本中的每个函数创建一个事件,然后将事件触发器注入函数的末尾。
通过这种方式,我可以准确地看到每个函数何时完成,并使用像其他函数的钩子这样的事件
如果我可以动态地执行它,我可以添加任意数量的新功能,而无需创建和追加这些事件。
这是我正在尝试做的一个基本示例,这实际上不会起作用,但它会给你一个想法。我一直在使用jQuery,但我会接受任何javascript框架,以及任何方法。
var obj = {};
(function()
{
this.init = function()
{
// loop through every function
$.each(this, function(k, v)
{
// create an event for every function
$('body').bind(v, function()
{
console.log('Event: ' + v + ' Finished');
});
// Add a event trigger into each specific function in the loop
this[v].call($('body').trigger(v));
});
}
this.another_function = function()
{
// do something
}
this.some_function = function()
{
/do something
}
}).apply(obj);
obj.init();
由于
(编辑)脚本本身基本上呈现一个日历,但有很多回调,ajax请求,按钮。等等...如果我可以将每个功能都绑定到一个事件,它将使我的生活更容易扩展它,添加新功能等...
答案 0 :(得分:1)
遍历每个函数,将其替换为新函数,在同一个对象上调用原始函数并触发正文上的事件。
var obj = { };
(function()
{
this.init = function()
{
var self = this;
foreach(var name in this) {
if (typeof k !== 'Function') continue;
if (name ==='init') continue;
var original = this[name];
var newFunc = function() {
original.apply(self, arguments);
$('body').trigger(name);
}
this[name] = newFunc;
}
}
this.another_function = function()
{
// do something
}
this.some_function = function()
{
/do something
}
}).apply(obj);
obj.init();