Create BOT terminal with Jquery#4 : Previous and next command and Create object in BOT

in #utopian-io6 years ago (edited)

Repository

https://github.com/jquery/jquery

What Will I Learn?

  • Previous and next command
  • Refactoring structure
  • Create object in BOT

Requirements

  • Html, CSS, javascript
  • Install Jquery and basic Jquery
  • Localserver (Xampp, Wampp, or etc)

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a continuation of the terminal bot tutorial series, you can see the curriculum below this tutorial, in the previous tutorial, We have learned how to make the commands we give to BOT can be dynamic regardless of certain commands. This time we will learn how to provide a better User experience for our BOT users, in the previous tutorial we have successfully displayed the previous command. We will also teach our BOT to know the Object. We just started to continue this tutorial series.

Make the prev command be dynamic

If you follow my previous tutorial then you must have learned how to display the previous command. We have done it successfully, but when we make that function, we make it statically or hardcode. the following is part of the code.

Code in the previous tutorial

 $('#terminal').keydown(function(e){
        if(e.keyCode==38){
          var data = $('.input').eq(-2).val();
          $('.input').last().val(data);
        }
})

We can see in this code $('.input').eq(-2).val();, we take the previous value in hardcode. we write -2, while we want the value to be dynamic according to how many times we press the down arrow or up arrow on our keyboard. to make it dynamic we will change the value -2 to a dynamic variable.

  • Make a function to handle (Arrow Up)

The idea is that I will make a variable that we will pass to replace the value -2, the variable is global, so we can watch the value. for more details, we can see the sample code below.

var index         = -2;
var indexChanged  = false; 
      $('#terminal').keydown(function(e){
        if(e.keyCode==38){
          if (indexChanged == true) index--;
          var data = $('.input').eq(index).val();
          $('.input').last().val(data);
          indexChanged = true;
        }
      });
  • Create the variable value: We will use the basic values of the variables we define, namely index and indexChanged.

Index: The index is the initial value of the order to retrieve the value from the input, we can see how it is used in our code $('.input').eq(-2).val(); now we pass the index value in the eq() to make the value dynamic $('.input').eq(-2).val();.

indexChanged: This variable functions as a validation whether the up arrow has been pressed more than once, so the initial value is false. We will change the indexChange value to true after we have pressed the up arrow.

  • Making validation logic: We will use the indexChanged variable as a reference to validate whether the user has pressed the up arrow or not. If indexChanged is true then we will decrease the index value if (indexChanged == true) index--;.

  • Passing dynamic value: We can pass the dynamic value contained in the variable index to replace the static value -2 $('.input').eq(index).val();.

  • Change the indexChanged value: After we execute the command we will change the indexChange value which was false to true so that our condition can be fulfilled indexChanged = true;. If there is no error we can run our local server and see the results as shown below:

ezgif.com-video-to-gif (2).gif

  • Make a function to handle (Arrow Down)

Not many changes to handle the down arrow, what we will do is change the algorithm in our program, if at arrow up we decrease the value in the index with index--; then in arrow down we increase values to the index with index++; and in the down arrow handle we no longer need to change the indexChange value to true because automatically the arrow up function has changed it. for more details, we can see in the code below.

 $('#terminal').keydown(function(e){
        //arrow up
        if(e.keyCode==38){
          console.log("arrow up pressed")
          if (indexChanged == true) index--;
          var data = $('.input').eq(index).val();
          $('.input').last().val(data);
          indexChanged = true;
        }
        //arrow down
        if(e.keyCode==40){
          console.log("arrow down pressed")
          if (indexChanged == true) index++;
          var data = $('.input').eq(index).val();
          $('.input').last().val(data);
        }
      });
  • Keycode for the down arrow: We can detect if the down arrow is pressed on the keyboard with keycode 40 if(e.keyCode==40), this is a rule. You can see another keycode here http://keycode.info/. then if on the up arrow we decrease the value index--; then in the down arrow we increase the value index++;. I will do console.log () so we can see what is happening behind. We can see the results in the picture below:

ezgif.com-video-to-gif (3).gif

Create objects on BOT

We have made functions so that the bot terminal book can run well, but the function is the unstructured mess we will react our code to be neater the same time we will learn how to create an object in our terminal BOT. I will create a variable object with the name _objectBot {}, then we will enter these functions into the object, for more details we can see in the example below.

  • Difference in writing

There is a slight difference in the way of writing, we will compare the way of writing at the bottom below:

Before

  function doResponse(msg){
        $('#terminal').append("<div class='res_bot'>"+ msg +"</div>")
      }
      function commandBot(){
        $('#terminal').append("<br><span>$bot : </span> <input class='input' name='input' placeholder='_'>")
      }
      function openLink(link){
        var newLink =  link.includes("https://");
        if(newLink){
          window.open(link, '_blank');
        }else{
          newLink = "https://"+link;
          window.open(newLink, '_blank');
        }
      }

After

  var _objectBot = {
           doResponse: function(msg){
            $('#terminal').append("<div class='res_bot'>"+ msg +"</div>")
          },
           commandBot: function(){
            $('#terminal').append("<br><span>$bot : </span> <input class='input' name='input' placeholder='_'>")
          },
           openLink: function(link){
            var newLink =  link.includes("https://");
            if(newLink){
              window.open(link, '_blank');
            }else{
              newLink = "https://"+link;
              window.open(newLink, '_blank');
            }
          }
      };
  • We can see some differences, If on the object we write the function name as follows functionName: function()
  • Then when we enter our function into the object we must separate the other functions with comma (,).

  • Difference in usage

Not only in writing, to change these functions into objects, we also have to change the way they are used, but we will also change our codes like the example below:

Before

$('#terminal').on('keyup', '.input',function(e){
        if(e.keyCode == 13){
          var value = $(this).val().trim().split(' ');
          if( value == ''){
            doResponse("Command not recognized")
          }else{
            if(value[0] == "open"){
              openLink(value[1])
            }else {
              doResponse('Command not found');
              $.post("api/index.php", { command: value[0], table:value[1], column:value[2] },
                function(response){
                  if(response.length ==0){
                     doResponse('Column not found');
                  }else{
                    for (var i = 0; i < response.length; i++) {
                      doResponse('title : '+response[i].title+' Description : '+ response[i].description);
                    }  
                  }
                commandBot();
              });
            }
          }
        }
      });



After

  $('#terminal').on('keyup', '.input',function(e){
        if(e.keyCode == 13){
          var value = $(this).val().trim().split(' ');
          if( value == ''){
            _object.doResponse("Command not recognized")
          }else{
            if(value[0] == "open"){
              _object.openLink(value[1])
            }else {
              _object.doResponse('Command not found');
              $.post("api/index.php", { command: value[0], table:value[1], column:value[2] },
                function(response){
                  if(response.length ==0){
                     _object.doResponse('Column not found');
                  }else{
                    for (var i = 0; i < response.length; i++) {
                      _object.doResponse('title : '+response[i].title+' Description : '+ response[i].description);
                    }  
                  }
                _object.commandBot();
              });
            }
          }
        }
      });
  • To access the function in the object we need to use the prefix name of the object before the name of the function like this _objectBot.functionName() as we have made, the name of the object is _objectBot.

  • to access properties in an object, we can use this keyword. to see the results we can see in the picture below.

  • Result command previous and next

Now we will try the function in the function to display the command previous and next, the following results:

ezgif.com-video-to-gif (4).gif

  • Result select table in database

We will also check whether the function is running on the function to check the table in the database if it works then the results will be as follows.

ezgif.com-video-to-gif (5).gif

We have completed this tutorial series, we have learned how to create objects and also how to make previous and next commands on our bot terminal, I hope you can develop this tutorial again so that our bot terminals have more uses and so you can get to know jquery and more usage, hopefully this tutorial helps you thank you

Curriculum

Bot Jquery#1 Preparation, input and output
Bot Jquery#2 Create database, Ajax process, Display data
Bot Jquery#3 Access database columns, Validation command, Get the previous command

Proof of workdone

https://github.com/milleaduski/botJquery

Sort:  

Thank you for your contribution.
While I liked your tutorial, below are few suggestions for improvement:

  • The concepts reflected in the tutorial are too short and basic, we recommend extending your tutorials a bit further to illustrate more key functionality in such implementation
  • Your English language and content structure can be broken at a lot of times, please work on improving this.
  • Your code samples included the use of "_object", which you actually referenced "_objectBot" in your comments and your actual github implementation. Please review your code before finalizing it.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thanks @mcfarhat , i forgot to push, the last change in my github. Noted

Thank you for your review, @mcfarhat!

So far this week you've reviewed 1 contributions. Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.029
BTC 56278.39
ETH 2377.99
USDT 1.00
SBD 2.29