JSLint “eval is evil.” alternatives

后端 未结 7 1359
别那么骄傲
别那么骄傲 2021-02-13 22:49

I am have some JavaScript functions that run on both the client (browser) and the server (within a Java Rhino context). These are small functions - basically little validators

7条回答
  •  忘了有多久
    2021-02-13 23:37

    Dont encode a function as a string in JSON. JSON is for content, which you are confounding with behavior.

    Instead, I suppose you could return JS files instead, which allow real functions:

     { name : "phoneNumber",
        policies : [ 
            { policyFunction : function() {
                  whateverYouNeed('here');
              }
            }
          ]
      }
    

    But while that solves the technical issue, it's still not a great idea.


    The real solution here is to move your logic out of your content entirely. Import a JS file full of little validation functions and call them as needed based on a dataType property in your JSON or something. If this functions are as small and portable as you say, this should be trivial to accomplish.

    Getting your data all tangled up with your code usually leads to pain. You should statically include your JS, then dynamically request/import/query for your JSON data to run through your statically included code.

提交回复
热议问题