0

I have a javascript request like this to pass data to play framework and based on the different propertyKey, the event should have different parameter.

I do something like this.

The js is used by multiple windows. So this._propertyKey will change based on different windows.

_postEvent: function(customData) {
 var propertyKey = this._propertyKey;
 var Event = {
       propertyKey : customData
     },
     url = play.url({
       alias: 'controllers.eventController.trackEvent',
       args: Event,
       withCsrf: true
     });
 return $.ajax(url, {
   type: 'POST'
 });
},

The problem when I trigger this code. According to the request it sends, it is always Event.propertyKey instead of the customized propertyKey I pass in. For example, if for this window, propertyKey = 'region'. I want 'region' to pass in as the parameter. But no matter what propertyKey is, the post request always sends Event.propertyKey = XXX instead of Event.region = XXX.

Is there a way to pass in the propertyKey here Is use to make it change dynamically based on different pages?

Haowen Cao
  • 145
  • 1
  • 5
  • What is `this`? Did you set it somewhere? Otherwise its value is `window` – 4castle Mar 30 '16 at 23:52
  • I do not specify this. It should be window. This js is shared by multiple windows, that's why the propertyKey will change each time. – Haowen Cao Mar 30 '16 at 23:55
  • Actually, I just learned that what I said about `window` is incorrect. I'm going to post an answer. – 4castle Mar 31 '16 at 00:01

1 Answers1

0

When a function is called as a method of an object, its this is set to the object the method is called on. MDN Reference

To fix that part of the code, use window instead of this.

In order to set a property name to be the value of another variable, you have to create the object first, and then set the key/value pair using []. SO Reference

var Event = {};
Event[propertyKey] = customData;
var url = play.url({
    alias: 'controllers.eventController.trackEvent',
    args: Event,
    withCsrf: true
});
Community
  • 1
  • 1
4castle
  • 32,613
  • 11
  • 69
  • 106