You need to sign in or sign up before continuing.
js-framework-syntax-js.md 10.0 KB
Newer Older
G
ge-yafang 已提交
1
# JavaScript
Z
zengyawen 已提交
2 3


G
ge-yafang 已提交
4
You can use a .js file in the ECMAScript compliant JavaScript language to define the service logic of an HML page. With dynamic typing, JavaScript can make your application more expressive with a flexible design. The following describes the JavaScript compilation and running.
Z
zengyawen 已提交
5 6


G
ge-yafang 已提交
7
## Syntax
Z
zengyawen 已提交
8

G
ge-yafang 已提交
9
The ES6 syntax is supported.
Z
zengyawen 已提交
10

G
ge-yafang 已提交
11 12
- Module declaration
  Import functionality modules.
Z
zengyawen 已提交
13

G
ge-yafang 已提交
14 15 16 17
  
  ```
  import router from '@system.router';
  ```
Z
zengyawen 已提交
18

G
ge-yafang 已提交
19 20
- Code reference
  Import JavaScript code.
Z
zengyawen 已提交
21

G
ge-yafang 已提交
22 23 24 25
  
  ```
  import utils from '../../common/utils.js';
  ```
Z
zengyawen 已提交
26 27


G
ge-yafang 已提交
28
## Objects
Z
zengyawen 已提交
29

G
ge-yafang 已提交
30 31 32 33
- Application Object
    | Attribute | Type | Description | 
  | -------- | -------- | -------- |
  | $def | Object | Object that is exposed in the app.js file and obtained by this.$app.$def.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:<br/>> Application objects do not support data binding. Data update should be triggered on the UI. | 
Z
zengyawen 已提交
34

G
ge-yafang 已提交
35
  Example Code
Z
zengyawen 已提交
36

G
ge-yafang 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  
  ```
  // app.js
  export default {
    onCreate() {
      console.info('AceApplication onCreate');
    },
    onDestroy() {
      console.info('AceApplication onDestroy');
    },
    globalData: {
      appData: 'appData',
      appVersion: '2.0',
    },
    globalMethod() {
      console.info('This is a global method!');
      this.globalData.appVersion = '3.0';
Z
zengyawen 已提交
54
    }
G
ge-yafang 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
  };
  ```

  
  ```
  // index.js
  export default {
    data: {
      appData: 'localData',
      appVersion:'1.0',
    },
    onInit() {
      this.appData = this.$app.$def.globalData.appData;
      this.appVersion = this.$app.$def.globalData.appVersion;
    },
    invokeGlobalMethod() {
      this.$app.$def.globalMethod();
    },
    getAppVersion() {
      this.appVersion = this.$app.$def.globalData.appVersion;
Z
zengyawen 已提交
75
    }
G
ge-yafang 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  }
  ```

- Page objects
    | Attribute | Type | Description |
  | -------- | -------- | -------- |
  | data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The attribute name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (for, if, show, and tid).<br/>Do not use this attribute and private or public at the same time. |
  | $refs | Object | DOM elements or child component instances that have registered the ref attribute. For example code, see [Obtaining a DOM element](#obtaining-a-dom-element). |
  | private | Object | Data model of the page. Private data attribute can be modified only on the current page. |
  | public | Object | Data model of the page. Behaviors of public data attributes are the same as those of the data attribute. |
  | props | Array/Object | Used for communication between components. This attribute can be transferred to components via &lt;tag xxxx='value'&gt;. A props name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (for, if, show, and tid). Currently, props does not support functions. For details, see [Custom Component](../reference/arkui-js/js-components-custom-props.md). |
  | computed | Object | Used for pre-processing an object for reading and setting. The result is cached. The name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words. For details, see [Custom Component](../reference/arkui-js/js-components-custom-props.md). |

## Functions

- Data functions
    | Function | Parameter | Description | 
  | -------- | -------- | -------- |
  | $set | key: string, value: any | Adds an attribute or modifies an existing attribute.<br/>Usage:<br/>this.$set('_key_',_value_): Add an attribute. | 
  | $delete | key: string | Deletes an attribute.<br/>Usage:<br/>this.$delete('_key_'): Delete an attribute. | 

  Example Code

  
  ```
  // index.js
  export default {
    data: {
      keyMap: {
        OS: 'OpenHarmony',
        Version: '2.0',
Z
zengyawen 已提交
107
      },
G
ge-yafang 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    },
    getAppVersion() {
      this.$set('keyMap.Version', '3.0');
      console.info("keyMap.Version = " + this.keyMap.Version); // keyMap.Version = 3.0
  
      this.$delete('keyMap');
      console.info("keyMap.Version = " + this.keyMap); // log print: keyMap.Version = undefined
    }
  }
  ```

- Public functions
    | Function | Parameter | Description |
  | -------- | -------- | -------- |
  | $element | id: string | Obtains the component with a specified ID. If no ID is specified, the root component is returned. For example code, see [Obtaining a DOM element](#obtaining-a-dom-element).<br/>Usage:<br/>```<div id='_xxx_'></div>```<br/>- this.$element('_xxx_'): Obtain the component whose ID is _xxx_.<br/>- this.$element(): Obtain the root component. |
  | $rootElement | None | Obtains the root element.<br/>Usage: this.$rootElement().scrollTo({ duration: 500, position: 300 }), which scrolls the page by 300 px within 500 ms. |
  | $root | N/A | Obtains the root ViewModel instance. For example code, see [Obtaining the ViewModel](#obtaining-the-viewmodel). |
  | $parent | N/A | Obtains the parent ViewModel instance. For example code, see [Obtaining the ViewModel](#obtaining-the-viewmodel). |
  | $child | id: string | Obtains the ViewModel instance of a custom child component with a specified ID. For example code, see [Obtaining the ViewModel](#obtaining-the-viewmodel).<br/>Usage:<br/>this.$child('_xxx_'): Obtain the ViewModel instance of a custom child component whose ID is _xxx_. |

- Event function
    | Function | Parameter | Description |
  | -------- | -------- | -------- |
  | $watch | data: string, callback: string \| Function | Listens for attribute changes. If the value of the data attribute changes, the bound event is triggered. For details, see [Custom Component](../reference/arkui-js/js-components-custom-props.md)<br/>Usage:<br/>this.$watch('_key_',_callback_) |

- Page function
    | Function | Parameter | Description |
  | -------- | -------- | -------- |
  | scrollTo<sup>6+</sup> | scrollPageParam:  ScrollPageParam | Scrolls the page to the target position. You can specify the position using the ID selector or scrolling distance. |

    Table1 ScrollPageParam<sup>6+</sup>
  
  | Name | Type | Default Value | Description |
  | -------- | -------- | -------- | -------- |
  | position | number | - | Position to scroll to. |
  | id | string | - | ID of the element to be scrolled to. |
  | duration | number | 300 | Scrolling duration, in milliseconds. |
  | timingFunction | string | ease | Animation curve for scrolling. Available option:<br/>[Animation Styles](../reference/arkui-js/js-components-common-animation.md) |
  | complete | () => void | - | Callback to be invoked when the scrolling is complete. |

  Example:

  
  ```
  this.$rootElement.scrollTo({position: 0})
  this.$rootElement.scrollTo({id: 'id', duration: 200, timingFunction: 'ease-in', complete: ()=>void})
  ```


## Obtaining a DOM Element

1. Use $refs to obtain a DOM element.
  
   ```
   <!-- index.hml -->
   <div class="container">
     <image-animator class="image-player" ref="animator" images="{{images}}" duration="1s" onclick="handleClick"></image-animator>
   </div>
   ```

   
   ```
   // index.js
   export default {
     data: {
       images: [
         { src: '/common/frame1.png' },
         { src: '/common/frame2.png' },
         { src: '/common/frame3.png' },
       ],
     },
     handleClick() {
       const animator = this.$refs.animator; // Obtain the DOM element whose $refs attribute is animator.
       const state = animator.getState();
       if (state === 'paused') {
         animator.resume();
       } else if (state === 'stopped') {
         animator.start();
       } else {
         animator.pause();
       }
     },
   };
   ```

2. Call $element to obtain a DOM element.
  
   ```
   <!-- index.hml -->
   <div class="container">
     <image-animator class="image-player" id="animator" images="{{images}}" duration="1s" onclick="handleClick"></image-animator>
   </div>
   ```

   
   ```
   // index.js
   export default {
     data: {
       images: [
         { src: '/common/frame1.png' },
         { src: '/common/frame2.png' },
         { src: '/common/frame3.png' },
       ],
     },
     handleClick() {
       const animator = this.$element('animator'); // Obtain the DOM element whose ID is animator.
       const state = animator.getState();
       if (state === 'paused') {
         animator.resume();
       } else if (state === 'stopped') {
         animator.start();
       } else {
         animator.pause();
       }
     },
   };
   ```

## Obtaining the ViewModel
Z
zengyawen 已提交
228 229 230

The following shows files of the root page:

G
ge-yafang 已提交
231

Z
zengyawen 已提交
232 233 234 235 236 237 238 239 240 241 242
```
<!-- root.hml -->
<element name='parentComp' src='../../common/component/parent/parent.hml'></element>
<div class="container">
  <div class="container">
    <text>{{text}}</text>
    <parentComp></parentComp>
  </div>
</div>
```

G
ge-yafang 已提交
243

Z
zengyawen 已提交
244 245 246 247 248 249 250 251 252 253 254
```
// root.js
export default {
  data: {
    text: 'I am a root!',
  },
}
```

Customize the parent component.

G
ge-yafang 已提交
255

Z
zengyawen 已提交
256 257 258 259 260 261 262 263 264 265
```
<!-- parent.hml -->
<element name='childComp' src='../child/child.hml'></element>
<div class="item" onclick="textClicked">
  <text class="text-style" onclick="parentClicked">Click this parent component</text>
  <text class="text-style" if="{{show}}">Hello parent component!</text>
  <childComp id = "selfDefineChild"></childComp>
</div>
```

G
ge-yafang 已提交
266

Z
zengyawen 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
```
// parent.js
export default {
  data: {
    show: false,
    text: 'I am the parent component!',
  },
  parentClicked () {
    this.show = !this.show;
    console.info('parent component get parent text');
    console.info(`${this.$parent().text}`);
    console.info("The parent component gets the child function.");
    console.info(`${this.$child('selfDefineChild').childClicked()}`);
  },
}
```

Customize the child component.

G
ge-yafang 已提交
286

Z
zengyawen 已提交
287 288 289 290 291 292 293 294
```
<!-- child.hml -->
<div class="item" onclick="textClicked">
  <text class="text-style" onclick="childClicked">Child component clicked</text>
  <text class="text-style" if="{{show}}">Hello child component</text>
</div>
```

G
ge-yafang 已提交
295

Z
zengyawen 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
```
// child.js
export default {
  data: {
    show: false,
    text: 'I am the child component!',
  },
  childClicked () {
    this.show = !this.show;
    console.info('child component get parent text');
    console.info('${this.$parent().text}');
    console.info('child component get root text');
    console.info('${this.$root().text}');
  },
}
```