简体   繁体   English

如何使用面向对象的javascript处理事件

[英]how to handle events using object oriented javascript

For example, i have an event object which collects information about an interaction by the user. 例如,我有一个事件对象,该对象收集有关用户交互的信息。 Here the event might be a button click or page reload or click on a tabbed menu etc. Means any action on the page could be captured by this event object. 这里的事件可能是单击按钮或重新加载页面或单击选项卡式菜单等。这意味着该事件对象可以捕获页面上的任何操作。 Can any one please suggest me how to achieve this using Object oriented javascript. 谁能建议我如何使用面向对象的javascript实现这一目标。 Like for example, see the below code snippet: 例如,请参见下面的代码片段:

digitalEvent.event[n].eventInfo = {
    eventName: "Login",
    eventAction: "login",
    type: "click",
    loginLocation:"somelocation",
    timestamp: new Date()
}

This would be an object but on a page how to handle or capture events like click by a user etc. 这将是一个对象,但是在页面上如何处理或捕获事件,例如用户单击等。

Thanks... 谢谢...

有一个全局的jQuery Event( https://api.jquery.com/category/events/event-object/ ),也许您可​​以使用其原型并进行自定义操作

For a start, the following code will handle all events triggered for the window object. 首先,以下代码将处理为window对象触发的所有事件。 You might want to handle specific onkeydown keycodes. 您可能要处理特定的onkeydown密钥代码。 As for capturing page reload and retaining your object's value, you will need to store it inside a cookie or Local Storage on onbeforeunload. 至于捕获页面重新加载并保留对象的值,则需要在onbeforeunload上将其存储在Cookie或本地存储中。

for (var property in window) {
    var match = property.match(/^on(.*)/)
    if (match) { 
        window.addEventListener(match[1] ,function(event){
           console.log(event.type + " , " + event.timeStamp);
           //store any information inside the object
        }, false); 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM