The _javascript skill of the small-letter micro-procedure of the Adzuki Bean book Example

Source: Internet
Author: User
Tags documentation string format

Recently micro-letter Small program was fired very hot, I also hold a try attitude to download the Micro-trust web Developer tools, development tools are relatively simple, less functional, personalized settings are not. After you've learned the development tools, you've looked at the official development documentation for the small program and probably learned about the development process of the applet and some common APIs.

Understand the small program, they have to want to do a small demo of the impulse, although the small program has not done a lot of practice, but in the official example of wandering, but still want to make a little thing. Since to do a demo, naturally need to data, they do not want to set up the service side alone, so the online search can be used to provide test data free API, and finally I chose the Watercress book. Watercress books provide less API functionality, plus not open appkey applications, so the user data can not be manipulated. Can only do some simple book inquiries and book details display, this demo only two pages, very simple.

Watercress Book API

Demo used in the Watercress book API only two, one is the book search, the other is to obtain book details.

Search for books

Get Https://api.douban.com/v2/book/search

Parameters meaning Notes
Q Query keywords Q and tag must be transmitted first
Tag Tag for Query Q and tag must be transmitted first
Start Offset of the result Default is 0
Count The number of bars to take the result Default is 20, maximum is 100

Back to status=200

{
 ' start ': 0, '
 count ': ' Total
 ': ' Books
 ': [Book, ...]
}

Get book details

Get Https://api.douban.com/v2/book/:id

Parameters meaning
: ID Book ID

The following is the details of specific books, part of the demo is not used in the information omitted

{"
  id": "1003078",
  "title": "Little Prince",
  "alt": "https:\/\/book.douban.com\/subject\/1003078\/",
  "image ":" Https://img3.doubanio.com\/mpic\/s1001902.jpg ","
  author ": [
    " (French) Saint Exupery "
    ],
  " publisher ":" China Friendship Publishing Company ",
  " pubdate ":" 2000-9-1 ",
  " rating ": {" Max ": Ten," Numraters ": 9438," average ":" 9.1 "," Min ": 0},
  "Author_intro": "Saint Exupery (1900-1944) 1900, Maya Destlem ...",
  "Catalog": "Preface: the French rose \ n the little Prince of St. Exupéry chronology \ n"
}

Demo Writing

Create a project

Project named Doubanbookapp, project structure applet default structure

Doubanbookapp
  Pages
    index home
      index.js
      index.wxml
      index.wxss
    Detail Details page
      detail.js
      detail.wxml
      DETAIL.WXSS
  requests 
    api.js API address
    request.js Network request
  utils
    Tool
  app.js
  App.json
  APP.WXSS

The application of the main color palette referred to the color of the Watercress app, using a partial green.

Home

Home Top Display search input box, user input book name, click the Search button, display book list. Books may be a lot, not all of a sudden, need to use paging, the most common list of apps on the page is the pull load mode, according to the components provided by the applet, found a more consistent with the scene of the Scroll-view components, This component has a Bindscrolltolower event that is automatically triggered by pulling up to the bottom.

First make the static effect of the interface, and then integrate the API, because I am not sensitive to the interface design, so casually made a rough layout, see the past on the line, hey ~ ~

Index.wxml

<view class= "Search-container" > <input type= "text" placeholder= "Enter title search" ></input><icon type= " Search "size="/> </view> <scroll-view scroll-y= "true" style= "width:100%;p osition:relative;top:40px; height:200px "> <view style=" TEXT-ALIGN:CENTER;PADDING-TOP:50RPX;
  > <icon type= "Cancel" color= "Red" size= "/>" <view><text> did not find related books </text></view> </view> <view style= "TEXT-ALIGN:CENTER;PADDING-TOP:50RPX;"
  
  > <icon type= "search" size= "/> <view><text> watercress book </text></view> </view>

  <view class= "Header" > <text> Book 10 books </text> </view> <view class= "Common-list" > <view class= "List-item" > <view class= "Index-list-item" > <view class= "Cover" > <image CLA ss= "cover-img" src= "images/demo.png" ></image> </view> <view class= "Content" > <view cl ass= "title" >Book Plotting </view> <text class= "desc" >9.0/oopsguy/2016-07-08</text> </view> </view> & lt;/view> </view> <view class= "Refresh-footer" > <icon type= "Waiting" size= "color=" "Reed"/&G
  T

 </view> </scroll-view>

INDEX.WXSS

Page {background: #F2F1EE;}
 /*seach*/. search-container {position:fixed;
 top:0;
 right:0;
 left:0;
 Background-color: #42BD56;
 Color: #FFF;
 height:40px;
 Padding:0 10rpx;
z-index:100;
 }. Search-container input {background: #FFF;
 Color: #AAA;
 margin-top:5px;
 padding:5px 10rpx;
 height:20px;
BORDER-RADIUS:8RPX;
 }. search-container icon {position:absolute;
 top:10px;
RIGHT:20RPX;

}/*header*/. header {padding:20rpx 30rpx; header text {color: #A6A6A6;}
 /*common list*/. list-item {position:relative;
 Overflow:hidden}/*index list*/. index-list-item {background: #FFF;
 PADDING:15RPX 30rpx;
Overflow:hidden;
 }. index-list-item::active {background: #EEE;} index-list-item. cover {float:left;
 WIDTH:120RPX;
 HEIGHT:160RPX;
 Overflow:hidden} index-list-item. cover image.cover-img {width:120rpx;
HEIGHT:160RPX;
 }. Index-list-item. Content {MARGIN-LEFT:140RPX}. Index-list-item. title {display:inline-block; Height:90rpx;
 PADDING-TOP:20RPX;
Overflow:hidden;
 }. Index-list-item. desc {display:block;
 FONT-SIZE:30RPX;
 PADDING-TOP:10RPX;
 Color: #AAA;
 White-space:nowrap;
 Overflow:hidden;
Text-overflow:ellipsis;
 }. refresh-footer {text-align:center;
PADDING:10RPX 0;

 }

Book Detail Page

Book Detail page is to show the specific book information, the general home page through the book ID to get the book information in the display, the acquisition process may have delay, need a load effect to transition.

Detail.wxml

<view> <view class= "Cover-container" > <image src= "images/demo.png" ></image> </view> <view class= "Book-meta" > <view class= "meta-info" > <text class= "book-title" > Book title &LT;/TEXT&G
      T <text class= "Other-meta" > Author: Author name </text> <text class= "Other-meta" > Publishing house: XXX publishing house </text> ; text class= "Other-meta" > Published date:2010-05-07</text> </view> <view class= "range" > <text C lass= "Score" >0</text> <text class= "viewers" >0</text> </view> </view> <v Iew class= "Book-intro" > <view class= "intro-header" ><text> introduction </text></view> <text clas s= "Intro-content" > This is the book introduction </text> </view> <view class= "Book-intro" > <view class = "Intro-header" ><text> author </text></view> <text class= "Intro-content" > This is the author profile </t Ext> </view> </view> <loading> Loading ... </loading>

 

DETAIL.WXSS

Page {background: #EEE; cover-container {background: #42BD56;
  Text-align:center;
PADDING:50RPX 0;
  }. cover-container image {Display:inline-block;
  WIDTH:300RPX;
HEIGHT:400RPX;
  }. Book-meta {position:relative;
  PADDING:20RPX;
Overflow:hidden;
  }. Book-meta. range {Position:absolute;
  TOP:30RPX;
  RIGHT:20RPX;
  WIDTH:180RPX;
  Background: #FFF;
  PADDING:20RPX 10rpx;
  Text-align:center;
box-shadow:2px 2px 10px #CCC; }. Book-meta. meta-info {margin-right:200rpx}. meta-info text {Display:block}. book-title {Font-weight:bold
  ;
FONT-SIZE:50RPX;
  }. Other-meta {padding-top:10rpx;
  Color: #888;
FONT-SIZE:30RPX;
  }. Range text {Display:block;}. Range. score {font-size:50rpx;
Font-weight:bold;

}. Range. Starts {FONT-SIZE:40RPX}. Range. viewers {font-size:30rpx;}
  . book-intro {padding:20rpx;
FONT-SIZE:40RPX; }. Book-intro. intro-header {color: #888}. Book-intro. intro-content {Font-size:35RPX;
LINE-HEIGHT:45RPX;

 }

Completes the homepage and the detailed page static page, next is through the network request API to obtain the data, and displays to the page.

Network requests and data processing

To better manage the API, I put the API in a separate api.js file

Api.js

Const API_BASE = "Https://api.douban.com/v2/book";

Module.exports = {
 api_book_search:api_base + "/search",
 api_book_detail:api_base + "/:id"
}

Some of the most frequently used tool functions are placed in the util.js.

Util.js

function Isfunction (obj) {return
 typeof obj = = ' function ';
}

Module.exports = {
 isfunction:isfunction
}

The micro-letter applet provides a api:wx.request (OBJECT) for a network request, which is similar to the Ajax method of jquery, and I put the network request into the Request.js for easy invocation.

Request.js

 var API = require ('./api.js '); var utils = require ('..

/utils/util.js '); /** * Network request/function request (URL, data, SUCCESSCB, ERRORCB, COMPLETECB) {wx.request ({Url:url, method: ' GE
    T ', Data:data, Success:function (res) {utils.isfunction (SUCCESSCB) && SUCCESSCB (res.data);
    }, Error:function () {utils.isfunction (ERRORCB) && ERRORCB ();
    }, Complete:function () {utils.isfunction (COMPLETECB) && COMPLETECB ();
}
  }); /** * Search book/function Requestsearchbook (data, SUCCESSCB, ERRORCB, COMPLETECB) {request (API).
Api_book_search, data, SUCCESSCB, ERRORCB, COMPLETECB); /** * Get book details/function Requestbookdokdetail (ID, data, SUCCESSCB, ERRORCB, COMPLETECB) {Request API.
Api_book_detail.replace (': ID ', id), data, SUCCESSCB, ERRORCB, COMPLETECB);  } module.exports = {requestsearchbook:requestsearchbook, requestbookdokdetail:requestbookdokdetail} 

Home has book search and list display, pull load effect. The micro-letter applet does not have the concept of DOM operation, all the changes in the interface elements to change through the data, so need to be in the page in JS data in the declaration of many members.

When the user enters the data, input box inputs are bound to the Searchinputevent event, which captures the input data and updates the input data in the Searchkey.

Searchinputevent:function (e) {
  this.setdata ({searchkey:e.detail.value});
}

When the click on the Search button is to trigger the tap event, it binds the searchclickevent

Searchclickevent:function (e) {
  if (!this.data.searchkey) return
   ;
  This.setdata ({pageindex:0, pagedata: []});
  Requestdata.call (this);
}

RequestData the way to request a list of books

/**
 * Request book information * *
function RequestData () {
 var _this = this;
 var q = this.data.searchKey;
 var start = This.data.pageIndex;

 This.setdata ({loadingmore:true, isinit:false});
 Updaterefreshball.call (this);

 Requests.requestsearchbook ({q:q, Start:start}, (data) => {
  if (data.total = 0) {
   //No records
   _THIS.S Etdata ({totalrecord:0});
  else {
   _this.setdata ({
    pagedata: _this.data.pagedata.concat (data.books),
    Pageindex:start + 1,
    TotalRecord:data.total
   });
  }
 , () => {
  _this.setdata ({totalrecord:0});
 }, () => {
   _this.setdata ({loadingmore:false});}


The effect of pull load is a small ball constantly changing color, need a color list

Refresh Dynamic ball color
var iconcolor = [
 ' #353535 ', ' #888888 '
];

And then use a timer to dynamically change the color of the ball icon.

/**
 * Refresh pull load effect color ball
/function Updaterefreshball () {
 var cindex = 0;
 var _this = this;
 var timer = setinterval (function () {
  if (!_this.data[' Loadingmore ']) {
   clearinterval (timer);
  if (CIndex >= iconcolor.length)
   cindex = 0;
  _this.setdata ({footericoncolor:iconcolor[cindex++]});


Detailed page of the display need to go to the home page click on the specific book ID, so need to pass the value of the first page, here use the Wx.navigateto method of the small program geotechnical, to its specified URL parameters followed by the query string format parameters, the page will be jumped in the OnLoad method to get the value.

Jump to Detail Page
todetailpage:function (e) {
  var bid = E.currenttarget.dataset.bid;//book ID [data-bid]
  Wx.navigateto ({
   URL: ' ... /detail/detail?id= ' + bid
  });
}

Accept parameters in Detail.js

Onload:function (option) {
  this.setdata ({
   id:option.id
  });
}

In fact, the page of the small program with the usual HTML and CSS almost, but the page can not use the traditional HTML tags, but instead of a small program to provide a custom label, the small program for the support of the CSS also has restrictions, pay attention to which writing is not compatible with almost understand. Manipulating page changes are represented by data changes that are somewhat like react and Vue. The above demo uses the knowledge point is not many, mainly is the page data binding, the event binding, the template knowledge and the network request and so on related API. A closer look at the documentation also makes for a small example.

Final effect Diagram

Overall, demo is very simple, only two pages, the interface is ugly t_t, which is my first lesson in the small program.

Sample code

SOURCE Address: Demo download

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.