执行代码时发送事件

时间:2016-05-12 09:04:50

标签: javascript if-statement javascript-events

你真的坚持这个..我需要在执行加载模块隐藏模块代码时发送一个事件,然后才发送事件。关于如何实现这一目标的想法?

//加载模块

var inverval = setInterval(hideClass, 100);

function hideClass () {
    if ($(".class").hide().length > 0) clearInterval(inverval);
}

//隐藏模块

DigitalData.push({'event':Module, 'eventLabel':'Page'});

//两者都发生=向Google Analytics发送事件

log_bin_trust_function_creators

1 个答案:

答案 0 :(得分:0)

如果这是你唯一的选择,那么也许你错了。无论如何,让我们看看...只有在两个事件发生时才会发生。

var HandleTwoEvents = function (key1, key2) {
   this.count = 0;
   this.pack = [];
   $self = this;
   this.startListening = function(fn) {
      fn = fn || function () {}
      window.addEventListener(key1, function (ev) {
         if ($self.pack.indexOf(key1) < 0) {
            $self.pack.push(key1);
            $self.count++;
            if ($self.count == 2) { 
                fn(); 
                $self.count = 0;
            }
         } 
         console.log(key1, ev);
      });
      window.addEventListener(key2, function (ev) {
         if ($self.pack.indexOf(key2) < 0) {
            $self.pack.push(key2);
            $self.count++;
            if ($self.count == 2) { 
                fn(); 
                $self.count = 0;
            }
         }
         console.log(key2, ev);
      });
    }
}

原谅我,我总是使用这个功能来创建活动

function createEvent(name, obj) {
    var evt = document.createEvent("Event");
    evt.initEvent(name, true, true);
    evt.data = obj;
    dispatchEvent(evt);
}

现在,记录两个事件......

var both = new HandleTwoEvents("EventKeyOne", "EventKeyTwo");
both.startListening(function () {console.log("This means that both Events have taken place")});

现在,让我们来测试......

createEvent("EventKeyOne", {}); 
//key, data are the arguments ... function defined in startListening above does not execute, and upon inspection, both.count is seen to be 1
createEvent("EventKeyTwo", {});
//Now, function executes. 
//It also works if "EventKeyTwo" is raised before "EventKeyOne"

快乐的编码!

PS:我确定有一种更好的方法来处理$ self变量的使用,我想有一些函数绑定。我从来没有学过它。