Parameters
Code Example
Basic Usage
Shake to Refresh
Shake for Random Selection
Related APIs
my.offWatchShake
Stop watching for shakes
my.vibrate
Trigger device vibration
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Listen for device shake events.
| Property | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback when shake is detected |
| fail | Function | No | Callback on failure |
| complete | Function | No | Callback that always executes |
my.watchShake({
success() {
console.log('Device was shaken!');
}
});
Page({
onLoad() {
this.enableShakeRefresh();
},
enableShakeRefresh() {
my.watchShake({
success: () => {
my.vibrate();
this.refreshData();
// Re-enable shake detection
this.enableShakeRefresh();
}
});
},
refreshData() {
my.showLoading({ content: 'Refreshing...' });
my.request({
url: 'https://api.example.com/data',
success: (res) => {
this.setData({ items: res.data });
my.hideLoading();
}
});
}
});
Page({
data: {
options: ['Option A', 'Option B', 'Option C', 'Option D'],
selected: null
},
onLoad() {
this.startShakeDetection();
},
startShakeDetection() {
my.watchShake({
success: () => {
my.vibrate();
this.selectRandom();
this.startShakeDetection();
}
});
},
selectRandom() {
const { options } = this.data;
const randomIndex = Math.floor(Math.random() * options.length);
this.setData({ selected: options[randomIndex] });
}
});
my.watchShake only triggers once per call. To continuously detect shakes, call it again in the success callback.