0

So I have this JSON object given for my project. It contain multiple settings, some of them are strings some are booleans.

However I am unable to perform one thing, which is adding animation name from the object stored in variable.

aniFx.move(inner, {
    duration: 1,
    delta: aniFx.ease.bouncePast
});

Explanation

Inner: document.getElementById('inner');
Duration: time multiplied by 1000 in my animation script (aniFx)
Delta: Animation used for moving the inner element

So now that I explained, that is working perfectly fine, until I try to set delta from JSON object. Let's say for sake of this question that my JSON object contains only following:

_userObj = JSON.parse('{ "137340": { "effect": "aniFx.ease.swingTo" } }');

Now, why I am unable to do this for example:

aniFx.move(inner, {
    duration: 1,
    delta: _userObj['137340'].effect
});

I will get following error when I trigger the function...

Console will return:

console.log => aniFx.ease.swingTo
aniFx.move => Uncaught TypeError: string is not a function
dvlden
  • 2,402
  • 8
  • 38
  • 61

1 Answers1

1

You cannot package functions as JSON.

_userObj['137340'].effect

evaluates to just a string ("aniFx.ease.swingTo") that you try to pass as delta, which is then tried to be called as function when executing aniFx.move.

Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66
  • Is there a way to resolve this ? Nothing on my mind. – dvlden Oct 15 '14 at 19:29
  • Something like [this](http://stackoverflow.com/a/359910/1744702) could work. so you would pass this for the move function: window[_userObj['137340'].effect] – Roope Hakulinen Oct 15 '14 at 19:30
  • Unfortunately, not in my case :-/ ! _Uncaught TypeError: undefined is not a function_ – dvlden Oct 15 '14 at 19:36
  • 1
    That would only work if the value were a global variable, not an expression. You need to use `eval()`, with all the dangers it has. – Barmar Oct 15 '14 at 19:38
  • 1
    Well, as it isn't global, if there are only handful of possible values for that, you could use switch structure to match the string and on match point to that function like this: case _"aniFx.ease.swingTo": effect = aniFx.ease.swingTo;_ and then pass the effect for move function. – Roope Hakulinen Oct 15 '14 at 19:43
  • @Barmar - I tried `eval()` it works, but I'll rather skip using it. @Sanfor - Yeh I guess I could do that then... Thank you! – dvlden Oct 15 '14 at 19:44