Introduction to jQuery_4

Module 3.1.

Before Start

The following contents are the notes I took when learning jQuery on Edx.

Mainly for front-End Web developers, check here to get more details.

CONTENTS

Three parts:

Module3 : Asynchronous programming and Ajax

Module3 includes five parts:

  • Using promises
  • Web workers
  • Using deferred
  • JavaScript Object Notation
  • Calling the server

Uh, When I first learned it , I felt it was a little difficult for me to get the point, and now, I still have the feeling.

Let’s get to know something about the first three parts.

A promise is an object returned by functions in jQuery that take a long or variable amount of time. By using a promise, you can ensure your code executes whenever the operation completes, be notified of its success or failure, or potentially receive updates about an operation’s progress.

A deferred object allows you to create your own long running operations, allowing developers to use the same patterns provided by the promise object, and be updated when your operation completes.

web worker, an HTML5 feature allowing web developers to simulate threads in a web browser.

  • promises

    • Long running operations

      Any jQuery function that runs over a long period of time, such as an animation, or communicates with a remote server, such as Ajax calls, returns a promise.

    • promises events

      • done

        raised when the operation completes successfully.

        accepts one or more event handler functions.

        Example:

        // code to obtain promise object
        promise.done(function(data) {
            // data will contain the data returned by the operation
        });
        
      • fail

        raised when the operation has completed with an error.

        accepts one or more event handler functions.

        Example:

        // code to obtain promise object
        promise.fail(function(data) {
           // data will contain the data returned by the operation
        });
        
      • progress

        raised when the operation raises an alert about its current state.

        Not all operations raise progress events.

        accepts one or more event handler functions.

        Example:

        // code to obtain promise object
        promise.progress(function(data) {
           // data will contain the data returned by the operation
        });
        
      • Chaining

        add done and fail (and potentially progress) event handlers by chaining the method calls as demonstrated below :

        // code to obtain promise object
        promise.done(function(data) {
            // success
        }).fail(function(data) {
            // failure
        });
        
      • then

        a single function allowing you to register done, fail, and progress event handlers in one call.

        The sample below is identical to the chaining demonstration above.

        // code to obtain promise object
        promise.then(function(data) {
            // success
        }, function(data) {
            // failure
        });
        
  • Web workers

    • Creating a web worker

      made up of two components:

      the parent or calling script, and the worker or executing script.

      does not have direct access to the calling environment or the UI.

      use a messaging system to pass information to and from the worker.

      • Creating the worker script

        To create a web worker, you create a separate JavaScript file.

        The code in the file will execute immediately when the worker object is created from the calling script.

        self : represents the worker. self , has one function named postMessage and one event message.

        postMessage is used to send data to the calling environment.

        message is raised when the calling script has sent a message to the worker.

        // send a signal back to the calling script
        self.postMessage('hello from the worker!');
        
        // Receive a message from the calling environment
        self.addEventListener('message', function(e) {
            // the data property will contain the data passed from the calling script
        });
        
    • calling a web worker

      • calling a web worker

        to check to see if the brower supports web workers

        // Test if the browser supports web workers
        if(Worker == null) {
            alert('You need to upgrade your browser!');
        } else {
            // do your work here
        }
        
      • creating an instance of the Worker object

        var worker = new Worker('script-location.js');
        
        // Register event handler
        worker.addEventListener('message', function(e) {
            $('#output').append('<li>' + e.data + '</li>');
        });
        
        worker.postMessage('Started!');
        

    • Designing your web workers

      • creating a web worker that accepts status messages

        Code:

        // worker.js
        
        self.addEventListener('message', function(e) {
            if(e.data === 'START') {
                // Start message received.
                // Begin work
                startWork();
            } else if (e.data === 'STOP') {
                // Stop message received.
                // Perform cleanup and terminate
                stopWork();
            } else {
                // A different message has been received
                // This is data that needs to be acted upon
                processData(e.data);
            }
        });
        
        function startWork() {
            // code to start performing work here
            // send a message to the calling page
            // worker has started
            self.postMessage('STARTED');
        }
        
        function stopWork() {
            // cleanupp code here
            // stop the worker
            self.postMessage('STOPPED');
            self.close();
        }
        
        function processData(data) {
            // perform the work on the data
            self.postMessage('Processed ' + data);
        }
        
      • calling a web worker that accepts messages

        If you were using the worker that’s been designed above, you would use it by following a couple of basic steps.

        1. Create an instance of Worker, passing in the script.
        2. Add the event handler for the message event. Ensure the event handler can respond to the status messages and normal data.
        3. When you’re ready to start the worker’s work, call postMessage('START');
        4. When you’re done, send the stop message by calling postMessage('STOP');

        Code:

        // inside of HTML file
        
        var worker = new Worker('worker.js');
        
        worker.addEventListener('message', function(e) {
            if(e.data === 'STARTED') {
                // worker has been started
                // sample: update the screen to display worker started
                $('#output').append('<div>Worker started</div>');
            } else if(e.data === 'STOPPED') {
                // worker has been stopped
                // cleanup work (if needed)
                // sample: update the screen to display worker stopped
                $('#output').append('<div>Worker stopped</div>');
            } else {
                // Normal message. Act upon data as needed
                // Sample: display data on screen
                $('#output').append('<div>' + e.data + '</div>');
            }
        });
        
        // When you're ready, send the start message
        worker.postMessage('START');
        
        // Send data as needed
        worker.postMessage('sample data');
        
        // Stop worker when you're done
        worker.postMessage('STOP');
        
  • Using deferred

    • Deferred

      Deferred and promise seem very similar.The difference between the two is who uses which.

      Deferred is used to create, and manage, a promise object.

      A promise object is returned by a long running operation, and only allows you to register event handlers.

      Deferred is the server side. When create a long running function that will be called by other developers, you’ll use Deferredto return a promise.

      promise is the client side. When you call a long running function, it will return a promise.

    • When to use Deferred

      when you are creating a function that will take an unusual amount of time, say one that will be working with graphics, you will want to use Deffered to return a promise to the caller.

    • Breaking down using Deferred

      The basic steps are as follows.

      1. Create an instance of deferred: var deferred = $.Deferred();
      2. Start your asynchronous operation, typically using a worker
      3. Add the appropriate code to detect success and send the success signal: deferred.resolve()
      4. Add the appropriate code to detect failure and send the failure signal: deferred.reject()
      5. Return the promise: return deferred.promise();
      function beginProcessing() {
          // Create deferred object & make sure it's going to be in scope
          var deferred = new $.Deferred();
      
          // Create our worker (just like before)
          var worker = new Worker('./Scripts/deferred.js');
      
          // Register the message event handler
          worker.addEventListener('message', function (e) {
              // simple messaging - if the worker is ready it'll send a message with READY as the text
              if (e.data === 'READY') {
                  // No UI code
                  // Progress notification
                  deferred.notify('Worker started');
              } else if(e.data === 'COMPLETED') {
                  // processing is done
                  // No UI code
                  // Completed notification
                  deferred.resolve('Worker completed');
      
                  worker.terminate();
              }
          });
      
          return deferred.promise();
      }
      

学这一章的时候,作为一个前端小白,我的内心响起一个声音:尼玛这都是什么鬼?

说人话,附上我对这三个概念的理解:

欢迎拍砖,皮厚不怕疼:P

promise是一个需要运行很长时间的jQuery函数会返回的东东,告诉caller,函数的运行状态,caller可以根据状态来执行相应代码。

Worker是用来在进程中插一脚的东东,通过message来传递状态,什么时候开始运行worker script,什么时候结束。

Deferred呢?用来生成,管理promise。