开发者

How can I dynamically change a JS called from a client?

开发者 https://www.devze.com 2023-01-23 13:07 出处:网络
I have a html page with 2 buttons on it and a big javascript function that is executed every 10 ms. Each click on each button executes a javascript function that changes some variables used by the big

I have a html page with 2 buttons on it and a big javascript function that is executed every 10 ms. Each click on each button executes a javascript function that changes some variables used by the big javascript function and change its behaviour. In time the code got very complex and time consuming and I would like to move the entire calculation of variables over to the server side. Or, better yet I would like to generate the entire function on the server.

How can I dynam开发者_运维问答ically change the big javascript function when any of the 2 buttons is being pressed?


What you could do is once the button is pressed you make an Ajax request to the server side. There you generate the javascript code based on the button pressed and send it back. You can then eval the response and execute the appropriate function.


Grabbing a large script and executing it every 10 ms is bound to be slow.

Modifying a large script isn't that bad and then you only care about the execution plan of the script. (It doesn't matter how fast the server can generate the script the client will execute if you're sending it every 10 ms and it's super complicated. Client execution is going to cause the client to creep if not properly made.)

However have you considered just "fixing" your script so that it's a bit more compartmentalized. Surely the entirety of the function does not change every 10 ms? (On your site does it change from being a game of Pong to a looping weather radar graphic every 10 ms?)

compartimentalized javascript example (using jquery): Assumes you have two tags one with the class buttonA and one with the class buttonB. Clicking buttonA or buttonB changes internal values and then the script is executed.

var complicatedFunction = function(){
    //private variables and methods
    var a = 2, b = 3;

    //public variables and methods
    return {
        exec: function(el){
           //which button was pushed?
           if($(el).is('.buttonA')){
               a = 4;
               b = 8;
           } else {
               a = 10;
               b = 2;
           }
           alert('The result of a*b is ' +(a*b));
        }
    }
}();
$('.buttonA, .buttonB').click(function(){complicatedFunction.exec(this)});

Wish I could help more, if you post a code example maybe we can!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号