S. Lee
S. Lee

Reputation: 35

Is there a simple way to save all the properties of a Mouse Event?

New to Javascript, currently developing a Chrome extension that saves browsing data. Is there some "catch-all" method that gets all properties of, say, a mouse click, at once? Or do I just have to save each individual property manually?

Currently, I'm doing the latter and collecting data like this:

function saveClick(e)
{
  altKey = e.altKey;
  pageX = e.pageX;
  pageY = e.pageY;
  buttons = e.buttons;
}

Is there a simpler way to accomplish this task?

Upvotes: 2

Views: 207

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074445

You can save the object itself:

theEvent = e;

If for whatever reason you don't want to do that, you can copy the object's own properties using spread notation or Object.assign:

// Property spread
theEvent = {...e};

// Or Object.asign
theEvent = Object.assign({}, e);

...but I wouldn't be surprised if you found that some properties were inherited accessor properties rather than the object's own properties.

As frobinsonj mentions, you can also use destructuring so you only have to list the properties once. Your code seems to have those variables declared elsewhere and just set within the function, which you can do with destructuring like this:

({altKey, pageX, pageY, buttons} = e);

You need the () because otherwise in a statement context, { starts a block. (frobinsonj's example doesn't need them because of the var.)

Upvotes: 2

Related Questions