Accessing variable in .filter() scope with Mixpanel JQL

642 Views Asked by At

Working with Mixpanel & JQL I am trying to access a variable from the global scope in the .filter() function, so I could query only the desired records:

var selectedVal = 'foo';

MP.api.jql(function main() {
    return People()
        .filter(function(user) {
            // Compare with 'selectedVal'
            return user.properties["user-title"] == selectedVal;
        })
    ; 
}, selectedVal).done(function(results) {
    // ...
});

Error:

{"request": "/api/2.0/jql/", "error": "Uncaught exception ReferenceError: selectedVal is not defined\n return user.properties[\"user-title\"] == selectedVal;\n ^\n\nStack trace:\nReferenceError: selectedVal is not defined\n at :6:70\n"}

If anyone could point me in the right direction, that would be great. Thank you

Edit:

At the moment I'm using a workaround by fetching all People entities and filtering afterwards. This is not optimal at all and thus am still looking for a way to get the result set on a property condition of the People entity.

2

There are 2 best solutions below

0
On BEST ANSWER

Looking into the unminified mixpanel-platform JS, the jql() function accepts a params object as second argument:

...

jql: function(script, params, settings) {
  params = params || {};
  settings = _.extend({type: 'POST'}, settings);
  return this.query('/api/2.0/jql/', {
    script: String(script),
    params: JSON.stringify(params)
  }, settings, function(data) {
    return JSON.parse(data);
  });
},

...

Solution:

var params = {
    selectedVal : 'foo'
};

MP.api.jql(function main() {
    return People()
        .filter(function(user) {
            return user.properties["user-title"] == params.selectedVal;
        })
    ; 
}, params).done(function(results) {
    // ...
});
0
On

Use bind. You can declare the function outside of MP.api.jql block and inside that jql function, you would pass in as a parameter, main.bind(null,whatever).