Using JavaScript to Manipulate Lecture Posts
Learn to add functionality to manipulate lecture posts.
To update and delete the lecture notes, we need to connect the frontend developed in the last lesson with the WordPress REST API through JavaScript. This will enable us to make changes to a lecture note from the frontend and save those changes to the database. Using JavaScript, we will also delete the note from the frontend and the database at the same time.
With the Excellence folder open in VS Code, access the terminal by clicking the "View" option and choosing "Terminal." Run the start script using the
npm run start
command. The start script will watch for any changes in the code and recompile it.
Lecture class
We will create a new JavaScript file in the modules folder inside the src folder. We can name the file Lecture.js
. In this file, we will create a class named Lecture
. Every class has a constructor which initializes an object of the class. To check if the code is working, an alert popup with a test message is displayed when an object is created. The class has an events
method to handles different events like mouse clicks, keypresses and page loads etc. Finally, we have methods with actions that take place when events occur. The last line exports the module. The code below shows the skeleton of the class.
class Lecture{constructor(){alert("An object of Lecture class has been created");this.events();}events(){}//methods}export default Lecture;
After exporting the module, we will import it in index.js
file. This file is present in the src folder and is the entry point of the @wordpress/scripts
package. We can import the Lecture.js
file by providing its path and create an object of this class.
// CSS imports// Module/class importsimport Lecture from "./modules/Lecture"// Instantiate object of the module/classvar lecture = new Lecture()
After saving these changes, the code recompiles and when we reload the site, we can see the alert message pop up. This indicates that an object of the Lecture
class has ...