Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development Click Events


May 22, 2021 Mini Program Cloud Development Study Guide


Table of contents


Events are the way the view layer communicates to the logical layer, and when we click tap, touch touch, and press and hold the components of the longpress program that bind the event, the event is triggered and the corresponding event handler in the logical layer is executed.

The view layer of the small program framework is written by WXML and WXSS and presented by components. R eflects the data from the logical layer into a view, while sending events from the view layer to the logical layer. The logical layer processes the data and sends it to the view layer, while accepting event feedback from the view layer.

The page scrolls

Use the developer tool to create a new tapevent page (add a tapevent page directly on the first line of the app.json's page configuration item, which, since it is the first item, can be presented as the home page of the applet), and then enter the following code into the tapevent.wxml file:

  1. <button type="primary" bindtap="scrollToPosition">滚动到页面指定位置</button>
  2. <view class="pagetop" style="background-color:#333;width:100%;height:400px"></view>
  3. <button type="primary" bindtap="scrollToTop">滚动到页面顶部(返回顶部)</button>
  4. <view id="pageblock" style="background-color:#333;width:100%;height:400px"></view>

Here type="primary" introduces the style that weui adds to button. The function names scrollToPosition and scrollToTop can be defined by themselves, and then we'll add the event handler corresponding to the function names scrollToPosition and scrollToTop in the corresponding js file.

Enter the following code .js Page({}) of function in the page (') of the tapvent(i.e., with data:{} ' onLoad: function (options) { } . . .

  1. scrollToTop() {
  2. wx.pageScrollTo({
  3. scrollTop: 0,
  4. duration: 300
  5. })
  6. },
  7. scrollToPosition() {
  8. wx.pageScrollTo({
  9. scrollTop: 6000,
  10. duration: 300
  11. })
  12. },

When the user clicks on the button component, the appropriate event handler is found in page on the page. A fter saving the compilation, see if there is a page scrolling effect? The principle is that the two functions, scrollToTop() and scrollToPosition(), are actually scrolling APIs wx.pageScrollTo() that call the same little program, and we can consult the technical documentation for the specific parameters of the API.

Scroll through api technical documentation: wx.pageScrollTo (Object object).

In the official documentation we can see that the role of wx.pageScrollTo() is to scroll the page to the destination, supporting the selector and scroll distance in both ways

  • ScrollTop scrolls to the target location of the page in px, with a value of 0 to scroll to the top and a value of 600
  • Duration is the length of the scroll animation in ms, and 1 second is 1000 milliseconds

So how do you scroll to the position of the specified selector? Earlier we've added id and class selectors to view, just change the configuration information of the previous function to the following (note that if you add rather than modify, the function name will conflict, or you can use other function names):

  1. scrollToTop() {
  2. wx.pageScrollTo({
  3. duration: 3000,
  4. selector:".pagetop"
  5. })
  6. },
  7. scrollToPosition() {
  8. wx.pageScrollTo({
  9. duration: 300,
  10. selector:"#pageblock"
  11. })
  12. },

Small task: If you just bind the event on the component, that is, only bindtap , "scrollToPosition", but do not write the corresponding event handler scrollToPosition in the js file, see what the console Console will report wrong?

Don't mistake the button component for binding events Oh, remember the technical documentation gadget components we looked at in the gadget components? I n the Public Properties section, you can see that all components have the following property bind/catch, which is type EventHandler, and bindtap is a type of bind. T his means that all components of the small program can trigger event handlers in the above way, to achieve scrolling and so on. Use button as a case just to make it easy to show.

Naming conventions: JavaScript project names, function names, variables, etc. should follow the principles of simplicity and semantics. F unction names are recommended to be named using the hump method, such as scrollToTop, pageScrollTo, which starts with lowercase letters, and each subsequent word is capitaled and looks like a camel???? Hump-like.

Message prompt boxToast

Message prompt boxes are an interactive interface that mobile apps, H5 (WebApp), and applets often use. Enter the code at tapvent.wxml:

  1. <button type="primary" bindtap="toastTap">点击弹出消息对话框</button>

Enter the following code in js:

  1. toastTap() {
  2. wx.showToast({
  3. title: '购买成功',
  4. icon: 'success',
  5. duration: 2000
  6. })
  7. },

Message prompt technical documentation: wx.showToast (Object object).

  • Title: Is required, the content of the prompt
  • icon: There are only three options, success, loading, none, so you can test the effect of three different values yourself
  • Duration: Prompt delay time, default to 1500 milliseconds, or 1.5 seconds

Small tasks: Modify title, icon, and duration, and add image properties to see what different representations are available, and in which app have you seen similar message messages?

Modal dialog box

To make the interface more concise, you can use the shortcut Ctrl plus / (Mac for Command plus /) to comment out the code in wxml above, and the functions in the js file don't need to be commented

Continue adding code to the tapevent.wxml file using the developer tool, and this time we'll call the modal box of the small program (or emphasize that modeTap can be named arbitrarily according to the naming convention, just add the appropriate event handler in js to call the API):

  1. <button type="primary" bindtap="modalTap">显示模态对话框</button>

Then enter the following code .js the tapvent code:

  1. modalTap() {
  2. wx.showModal({
  3. title: '学习声明',
  4. content: '学习小程序的开发是一件有意思的事情,我决定每天打卡学习',
  5. showCancel: true,
  6. confirmText: '确定',
  7. success(res) {
  8. if (res.confirm) {
  9. console.log('用户点击了确定')
  10. } else if (res.cancel) {
  11. console.log('用户点击了取消')
  12. }
  13. }
  14. })
  15. },

After saving the compilation, click the button on the emulator to display a dialog box, which we call the Modal modal dialog box.

Modal dialog technical documentation: wx.showModal (Object object).

The ever-changing API

To read the API's technical documentation, you need to understand what the API's properties are, what they represent, what type they are (which is important), and what their default values are, and what values can be taken.

  • Title properties are not required, delete the assignment of title, will not show the title;
  • Content properties are not required, for the content of the prompt;
  • ShowCancel's default value is true, which means that the cancellation button is displayed by default, and the fact is not displayed instead of false
  • The default value of confirmText is OK, you can change it to something else to try

By assigning different values to properties already in the API, there are many variations in what the API presents, and how you use it will require you to use it based on the actual small program development project.

Small tasks: In which apps, applets, H5 (WebApp) do you see modal boxes? U nder what circumstances do these modal boxes appear and what does they do? Can you imitate these modal boxes and write configuration information?

Console .log the log

Click the cancel and OK button above the modal box to notice the log print information of Console, the developer tool debugger: when we click the cancellation button, "User clicks cancel" is printed, and when we click the OK button, "User clicks OK", and the print result is output by this code above:

  1. success(res) {
  2. if (res.confirm) {
  3. console.log('用户点击了确定')
  4. } else if (res.cancel) {
  5. console.log('用户点击了取消')
  6. }
  7. }

So how do you understand this code? I n addition .log console ('User clicks OK'), what is res, which has been in contact before? R es.confirm, res.cancel What is it and where did it come from? W e can use .log () print it. Add some print information to this code.

  1. success(res) {
  2. console.log(res)
  3. if (res.confirm) {
  4. console.log(res)
  5. console.log("点击确认之后的res.confirm是:" + res.confirm)
  6. console.log("点击确认之后的res.cancel是:" + res.cancel)
  7. } else if (res.cancel) {
  8. console.log(res)
  9. console.log('用户点击了取消')
  10. console.log("点击取消之后的res.confirm是:" + res.confirm)
  11. console.log("点击取消之后的res.cancel是:" + res.cancel)
  12. }
  13. }

Then compile and click on the cancellation and determination buttons of the modal box to see what the results are printed out. W hen you click Confirm, the value of res.confirm is true, the statement in the if branch is executed, and when the value of res.cancel is true, the statement of res.cancel is executed. In the modal dialog technical documentation: wx.showModal (Object object) also has a description of the object.success callback function.

success, fail, complete callback functions In the technical documentation, you can see that there are two callback functions in the properties, success and fail, which call a successful callback function for the interface, and fail to call a failed callback function for the interface. F or this knowledge, you can read the technical documentation small program API, get an overview of the parameters of the asynchronous API and callback function, understand that the execution results of the asynchronous API need to be obtained through the corresponding callback function passed in the parameters of the Object type. (It doesn't matter if you don't understand)

The phone vibrates

Mobile phone vibration API is divided into two kinds, one is long vibration, one is short vibration, two APIs write roughly the same, in order to experience the effect, we take long vibration as an example, in tapvent.wxml input the following code,

  1. <button type="primary" bindtap="vibrateLong">长振动</button>

Then add the corresponding .js in the tapvent file:

  1. vibrateLong() {
  2. wx.vibrateLong({
  3. success(res) {
  4. console.log(res)
  5. },
  6. fail(err) {
  7. console.error(err)
  8. },
  9. complete() {
  10. console.log('振动完成')
  11. }
  12. })
  13. },

After saving the compilation, click Preview and use your phone scan to experience the effects of long vibrations.

Long vibration technical documentation: wx.vibrateLong().

In the long vibration technical documentation we see three callback functions in the API again, success, fail, complete. W hen you click the button on the emulator, you can see the print log. console.error prints the error log to the console's console, which is generally a matter of phone permissions if long vibrations cannot be invoked.

Small tasks: Refer to the code for long vibrations and the technical documentation for short vibrations, write a case of short vibrations, and experience how the two are different.

Pop up the action menu

Let's take a look at how to do this and enter the following code at tapvent.wxml

  1. <button type="default" bindtap="actionSheetTap">弹出操作菜单</button>

Then add the corresponding .js in the tapvent file:

  1. actionSheetTap() {
  2. wx.showActionSheet({
  3. itemList: ['添加照片', '删除照片', '更新照片', '查询更多'],
  4. success(e) {
  5. console.log(e.tapIndex)
  6. }
  7. })
  8. },

Pop-up menu technical documentation: wx.showActionSheet (Object object).

After saving in the simulator experience, click the button will pop up to show add photos, delete photos, update photos, query more options and other options of the action menu menu after the operation menu is not reflective, click after the reaction also needs us to write the event handler later.

the success callback function

When we click on the different options in the action menu, we return different numbers, depending on the value of e.tapIndex in the success callback function. In the official documentation we can learn that when the user clicks the button serial number, from top to bottom order, starting from 0, corresponding to the serial number of the array itemList, which makes it possible for us to perform different operations according to different menu options in the future.

Small tasks: In the success(e) callback function, add the console.log(e) print e and the errMsg object of the console.log (e.err Msg) print e to see what the results are.

Page routing

Page routing is a very important concept, opening new pages, page returns, Tab page switching, page redirection, etc. are all different ways to route.

Regarding page routing, we can read the page routing technical document, page routing can be simply understood as the management of page links, according to different url links to display different content and page information. In the later chapters we will also be specific about the knowledge of page routing, do not have to be demanding to understand all at once.

Navigator components and page routing APIs

We've studied the Navigator component before, and in the technical documentation for the navigator component, we can see the open-type property as well as the legal value. Y ou can also see 5 different APIs on the left side of the small program API. The correspondence between them is as follows:

Page routing API Navigator open-type value Meaning
redirectTo redirect Close the current page and jump to a page within the app. However, jumping to the tabbar page is not allowed.
navigateTo navigate Keep the current page and jump to a page within the app. However, you cannot jump to the tabbar page.
navigateBack navigateBack Close the current page and return to the last or multi-level page.
switchTab switchTab Jump to the tabBar page and close all other non-tabBar pages
reLaunch reLaunch Close all pages and open a page within the app

That's what the Navigator component can do, and using JavaScript to call small programs can also route APIs. The contents of the Navigator component are written to death, while JavaScript provides dynamic data.

Jump to the new page with the Tab page

We can enter the following code in home.wxml, which we created earlier:

  1. <button bindtap="navigateTo">保留页面并跳转</button>
  2. <button bindtap="switchTab">跳转到组件Tab页</button>
  3. <button bindtap="redirectTo">关闭当前页面跳转</button>

Then add .js code to the home file:

  1. navigateTo() {
  2. wx.navigateTo({
  3. url: '/pages/home/imgshow/imgshow'
  4. })
  5. },
  6. switchTab() {
  7. wx.switchTab({
  8. url: "/pages/list/list",
  9. })
  10. },
  11. redirectTo() {
  12. wx.redirectTo({
  13. url: '/pages/home/imgshow/imgshow'
  14. })
  15. },

After saving, the switch between the page and the Tab page is achieved by clicking the button in the developer tool's simulator. As mentioned earlier, bintap is a public property of all components of a small program, and only bintap bintap binds the event handler for page routing switching, and it doesn't matter if the component is Avagator, that is, link jump is no longer the patent of the Navigator component.

Note the url path here, we are using an absolute path relative to the small root. App.json's pages configuration item is not in front of / because app.json is already in the root, so you can use the relative path and the values here, as well as many of the API parameters of the string String type assignment, single and double quotes are not affected.

Go back to the previous page

Enter the following code under imgshow.wxml under the imgshow folder in the home page (this page was built in the first part of the development of the small program, if not, you can create it again):

  1. <button bindtap="navigateBack">返回上一页</button>

Add the following code .js the imgshow page

  1. navigateBack() {
  2. wx.navigateBack({
  3. delta: 1
  4. })
  5. },

Click the Hold Page Jump button and the Back to Previous button so that we can switch pages and return pages in the small program by clicking on the components. And if you jump to a new page using wx.redirectTo, you can't use it to go back to the previous page.

wx.navigateTo is to keep the current page, jump to an in-app page, and use wx.navigateBack to return to the original page. For small programs that don't have a particularly large number of pages, and there are frequent switchovers between pages, it is recommended to use wx.navigateTo for jumps, and then return to improve loading speed.