├── LICENSE
├── README.md
├── bower.json
├── index.htm
├── package.json
└── source
├── smart.element.js
└── smart.element.min.js
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License and Custom License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | 10. INTELLECTUAL PROPERTY
177 | All intellectual property rights such as but not limited to patents, trademarks, copyrights or trade secret rights related to the Software are property of the Author. You shall not modify, translate, reverse engineer, un-minify, decompile or disassemble the Software or any portion of it or attempt to derive source code or create derivative works. You are not allowed to remove, alter or destroy any proprietary, trademark or copyright markings or notices related to the Software. You must not remove copyright headers, links and markings from any files included in the Software. You must obtain a permission by the Author if you need to incorporate the Software or any portions of it in open source projects.
178 |
179 | 11. NON-COMPETE
180 | You are not allowed to use any portion of the Software in any products that fully or partially resemble the functionality of the Software or otherwise compete with the Software. You are not allowed to use the Software in any products or solutions offering reusable user interface components to end users, developers and third parties without express written permission by the Author.
181 |
182 |
183 | END OF TERMS AND CONDITIONS
184 |
185 | APPENDIX: How to apply the Apache License to your work.
186 |
187 | To apply the Apache License to your work, attach the following
188 | boilerplate notice, with the fields enclosed by brackets "[]"
189 | replaced with your own identifying information. (Don't include
190 | the brackets!) The text should be enclosed in the appropriate
191 | comment syntax for the file format. We also recommend that a
192 | file or class name and description of purpose be included on the
193 | same "printed page" as the copyright notice for easier
194 | identification within third-party archives.
195 |
196 | Copyright [yyyy] [name of copyright owner]
197 |
198 | Licensed under the Apache License, Version 2.0 (the "License");
199 | you may not use this file except in compliance with the License.
200 | You may obtain a copy of the License at
201 |
202 | http://www.apache.org/licenses/LICENSE-2.0
203 |
204 | Unless required by applicable law or agreed to in writing, software
205 | distributed under the License is distributed on an "AS IS" BASIS,
206 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
207 | See the License for the specific language governing permissions and
208 | limitations under the License.
209 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [Smart Custom Element](https://www.htmlelements.com) [](https://twitter.com/intent/tweet?text=Get%20over%2020%20free%20custom%20elements%20based%20on%20SmartHTMLElements%20&url=https://www.htmlelements.com/&via=htmlelements&hashtags=bootstrap,design,templates,blocks,developers,webcomponents,customelements,polymer,material)
2 |
3 | [](https://smarthtmlelements.slack.com/)
4 | [](https://github.com/HTMLElements/smart-custom-element/blob/master/LICENSE)
5 | [](https://www.npmjs.com/package/@smarthtmlelements/smart-custom-element)
6 | [](https://github.com/HTMLElements/smart-custom-element)
7 | [](https://github.com/HTMLElements/smart-custom-element/blob/master/LICENSE)
8 | [](https://www.htmlelements.com)
9 | [](https://www.htmlelements.com)
10 |
11 | JavaScript library that wraps the W3C standard Web Components family of APIs to provide a compact, feature-rich interface for `Custom Elements` development.
12 |
13 | Smart Custom Element provides a set of useful API, Data Binding, Templates, Device Agnostic Event Handling, Resize handling, Style Change Notifications, Property and Attribute Change Notifications, Property Value and Type validation, Localization, Lifecycle callback functions and much more. Our framework allows you to easily build Custom HTML Elements. Custom Elements are the web platform's native solution for component-based development. With Custom Elements, you get reusable HTML tags that can be used just like the browser’s built-in native html elements, or break your app up into small pieces, making your code cleaner and easier to maintain.
14 |
15 | ## Installation
16 | - `npm install smart-custom-element --save`
17 |
18 | In your web page, include
19 |
20 | ```
21 |
22 |
23 | ```
24 |
25 | Optional polyfill for browsers without custom elements support: `webcomponents-lite.js`
26 |
27 |
28 | ## Version and Deployment
29 | - This package is version according to [semantic versioning](http://semver.org).
30 |
31 | ## Browser Support and Compatibility
32 |
33 | **[Requires ES2015 classes](https://caniuse.com/es6-class). Edge, Chrome, Safari and Firefox. Requires Webcomponents polyfill for Edge and Safari**
34 |
35 | - **If targeting browsers that natively support ES2015, but not native Web Components:**
36 |
37 | You will also need the [Shady DOM + Custom Elements polyfill](https://github.com/webcomponents/webcomponentsjs).
38 |
39 | See caniuse.com for support on [Custom Elements v1](https://caniuse.com/#feat=custom-elementsv1) and [Shadow DOM v1](https://caniuse.com/#feat=shadowdomv1)..
40 |
41 | ## How to Use?
42 |
43 | Include HTML tag (e.g. ```)``` in any time of document lifecycle. You can use your elements in e.g. SPA application just by including HTML tag. Custom Elements will auto initialize when added into document. You can include them in e.g. Vue, Angular or React projects and browser will take care of detecting it and initialization. You use it just like a native HTML Element, by changing attributes with ```button.setAttribute(attributeName, attributeValue);```, setting properties with ```button.disabled = true;``` or listening to events with ```button.addEventListener('click', function(event) { });```.
44 | You also take advantage of features like lazy-loading, that allows for loading components on demand, only when user add them to document
45 |
46 | ## Introduction
47 |
48 | A basic element definition looks like this:
49 |
50 | ```javascript
51 |
52 |
53 |
54 |
55 |
56 |
81 |
107 |
108 |
109 |
110 |
111 |
112 | ```
113 |
114 | An extended element definition looks like this:
115 |
116 | ```javascript
117 | Smart('smart-button', class Button extends Smart.ContentElement {
118 | // Button's properties.
119 | static get properties() {
120 | return {
121 | 'value': {
122 | type: 'string'
123 | },
124 | 'name': {
125 | type: 'string'
126 | },
127 | 'type': {
128 | type: 'string'
129 | },
130 | 'clickMode': {
131 | allowedValues: ['hover', 'press', 'release'],
132 | type: 'string',
133 | value: 'release'
134 | }
135 | };
136 | }
137 |
138 | /** Button's template. */
139 | template() {
140 | return '';
141 | }
142 |
143 | static get listeners() {
144 | return {
145 | 'button.mousedown': '_mouseDownHandler',
146 | 'button.mouseenter': '_mouseEnterHandler',
147 | 'button.click': '_clickHandler'
148 | };
149 | }
150 |
151 | _clickHandler(event) {
152 | const that = this;
153 |
154 | if (that.clickMode !== 'release') {
155 | event.preventDefault();
156 | event.stopPropagation();
157 | }
158 | }
159 |
160 | _mouseDownHandler() {
161 | const that = this;
162 |
163 | if (that.clickMode === 'press') {
164 | that.$.fireEvent('click');
165 | }
166 | }
167 |
168 | _mouseEnterHandler() {
169 | const that = this;
170 |
171 | if (that.clickMode === 'hover') {
172 | that.$.fireEvent('click');
173 | }
174 | }
175 | });
176 | ```
177 |
178 | The base custom element class is called `BaseElement` and is accessible through `Smart.BaseElement`. Most elements derive from `Smart.BaseElement`. `Smart.ContentElement` extends the `Smart.BaseElement` by adding `content` and `innerHTML` properties to it. It is useful when you need to append a child element by setting a single property.
179 |
180 | ## Register a Custom Element
181 |
182 | To register a custom element, use the `Smart` function and pass in the element's tag name and class. By specification, the custom element's name must contain a dash (-). The library internally checks whether Custom Elements v1 is supported and uses its lifecycle callbacks and customElements.define. Otherwise, it uses document.registerElement and the v0 lifecycle callbacks. To use custom elements, you will need a browser which natively supports Custom Elements or you will need to load polyfills such as `webcomponentsjs`.
183 |
184 | Resources:
185 |
186 | * https://developer.mozilla.org/en-US/docs/Web/Web_Components
187 | * https://developers.google.com/web/fundamentals/getting-started/primers/customelements
188 | * http://webcomponents.org/
189 | * **webcomponentsjs** polyfill:
190 | * https://github.com/webcomponents/webcomponentsjs
191 | * https://www.npmjs.com/package/@webcomponents/webcomponentsjs
192 | * The files **webcomponents-lite.js** and **webcomponents-loader.js** have to be referenced (in this order).
193 |
194 |
195 | ## Lifecycle callbacks
196 |
197 | * created - Called when the element has been created, but before property values are set and local DOM is initialized.
198 | Use for one-time set-up before property values are set.
199 | * attached - Called after the element is attached to the document. Can be called multiple times during the lifetime of an element.
200 | * ready - Called when the element is ready. Use for one-time configuration of your element.
201 | * detached - Called after the element is detached from the document. Can be called multiple times during the lifetime of an element.
202 | * completed - Called after the element and any custom elements in its template are ready, rendered and attached to the DOM. Completed is called once.
203 |
204 | ## Properties
205 |
206 | To add properties on your custom element, you can use the `properties` object. All properties part of the `properties` object are automatically serialized and deserialized by the element and can also be set through attributes by using the dash(-) syntax in the HTML markup. Each property can have the following members:
207 |
208 | * reflectToAttribute - Type: Boolean. Set to `true` to cause the corresponding attribute to be set on the host node when the property value changes. If the property value is `Boolean`, the attribute is created as a standard HTML boolean attribute (set if true, not set if false). For other property types, the attribute value is a string representation of the property value. The default value of this member is `true`.
209 | * defaultReflectToAttribute - Type: Boolean. Set to `true` when we want a default attribute value to be set on the host node.
210 | * readOnly - Type: Boolean. Determines whether the property is readyonly. if `true` the property can't be set by the user.
211 | * type - Type: String. Used for deserializing from an attribute.
212 | * any - allows assigning any value to a property.
213 | * string - allows assigning a `String` to a property.
214 | * string? - allows assigning a 'String' or null to a property.
215 | * boolean or bool - allows assigning a `Boolean` to a property.
216 | * boolean? or bool? - allows assigning a 'Boolean' or null to a property.
217 | * number or float - allows assigning a 'Number' to a property.
218 | * number? or float? - allows assigning a 'Number' or null to a property.
219 | * int or integer - allows assigning an 'Integer' to a property.
220 | * int? or integer? - allows assigning an 'Integer' or null to a property.
221 | * date - allows assigning a 'Date' to a property.
222 | * date? - allows assigning a 'Date' or null to a property.
223 | * array - allows assigning an 'Array' to a property.
224 | * object - allows assigning an 'Object' to a property.
225 | * allowedValues - Type: Array. Used for defining a set of values which are allowed to be set. For other values, an exception is thrown.
226 | * notify - Type: Boolean. Determines whether an event is raised when a property is changed. The event name is: property's attribute name + - 'changed'. Example: Property's name is 'clickMode', the event's name will be 'click-mode-changed'.
227 | Example:
228 | ```javascript
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
308 |
309 |
310 |
311 |
312 | Enable/Disable
313 |
314 |
315 |
316 | ```
317 | * value - Default value for the property.
318 | * observer - Type: String. A name of a function called within the Element when the property is changed. The arguments passed to your observer are the property's `oldValue` and `newValue`.
319 | * validator - Type: String. A name of a function called within the Element when the property is changing. The arguments passed to your validator are the property's `oldValue` and `newValue`. The function `returns` the updated value. If it `returns undefined`, the newValue remains unchanged.
320 |
321 | `propertyChangedHandler(propertyName, oldValue, newValue)` method is called when a property is changed by the user. This method is useful for updating the element when the user makes some changes.
322 |
323 | The user may watch for property changes by using the element's instance. `watch(propertiesArray, propertyChangedCallback)`. The arguments passed to the `propertyChangedCallback` function are `propertyName, oldValue, newValue`.
324 | ## Template
325 |
326 | The `template` object determines the internal HTML structure of the Element. Within that structure you can data bind properties by using two-way or one-way data binding.
327 |
328 | ```javascript
329 | template() {
330 | return '';
331 | }
332 | ````
333 |
334 | Text surrounded by double curly bracket ({{ }}) or double square bracket ([[ ]]) delimiters. Identifies the host element's property being bound.
335 |
336 | * Double-curly brackets (}) is used for two-way data flow.
337 | * Double square brackets ([[ ]]) is used for one-way downward from host element to target element data flow.
338 |
339 | Two-way binding to a Native HTML element.
340 | ```javascript
341 | nativeElementProperty="{{hostElementProperty::nativeElementEvent}}"
342 | ```
343 |
344 | ```javascript
345 | Smart('my-element', class MyElement extends Smart.BaseElement {
346 | static get properties() {
347 | return {
348 | 'check': {
349 | type: 'boolean'
350 | }
351 | };
352 | }
353 |
354 | template() {
355 | return '';
356 | }
357 | });
358 | ```
359 | ```HTML
360 |
361 |
362 |
363 |
364 |
365 |
366 |
374 |
375 |
376 |
377 |
378 |
379 | ```
380 |
381 | Content insertion point determines where the HTML elements which are within the custom element's body during initialization go during the initialization. By default that is the Custom Element itself, but you can specify a custom content insertion point, you can define a `content` tag within the template's structure as in the below example:
382 |
383 | ```javascript
384 | template() {
385 | return `
386 |
389 |
390 |
`;
391 | }
392 | ```
393 |
394 |
395 | After the template is parsed, each element of the HTML Structure is accessible via its `id` and the `$` symbol. Note the `checkboxInput` element in the below example:
396 |
397 | ```javascript
398 | /**
399 | * CheckBox custom element.
400 | */
401 | Smart('smart-checkbox', class CheckBox extends Smart.ToggleButton {
402 | // CheckBox's properties.
403 | static get properties() {
404 | return {
405 | 'enableContainerClick': {
406 | value: true,
407 | type: 'boolean'
408 | }
409 | };
410 | }
411 |
412 | /** Checkbox's Html template. */
413 | template() {
414 | return `
415 |
416 |
417 |
418 |
`;
419 | }
420 |
421 | static get listeners() {
422 | return {
423 | 'click': '_clickHandler'
424 | };
425 | }
426 |
427 | /** Called when the element is ready. Used for one-time configuration of the Checkbox. */
428 | ready() {
429 | }
430 |
431 | /** Changes the check state wneh widget container is clicked. */
432 | _clickHandler(event) {
433 | const that = this;
434 |
435 | if (that.disabled) {
436 | return;
437 | }
438 |
439 | const isInputClicked = event.target === that.$.checkboxInput;
440 |
441 | if ((that.enableContainerClick === true && !isInputClicked) || isInputClicked) {
442 | that._changeCheckState('pointer');
443 | that.focus();
444 | }
445 | }
446 | });
447 |
448 | ```
449 | A set of utility functions is accessible throught the `$` symbol. The syntax is `element.$`.The utilify functions are:
450 | * addClass(className) - adds a class or classes to the element separated by space.
451 | * removeClass(className) - removes a class or classes separated by space.
452 | * isNativeElement - returns `true` if the element is native HTML Element. Otherwise returns `false`.
453 | * fireEvent(eventType, detail, options) - fires a Custom Event.
454 | * eventType - String. Determines the event's type.
455 | * detail - Object. Determines custom event object passed to the user.
456 | * options - Object. Determines the event's options like `cancelable` or `bubbles`. Read more on: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
457 | * listen(eventType, handler) - adds an event listener to the element. A set of Mobile-friendly events are supported by default. By passing any of these event types: `down, up, move, tap, taphold, swipeleft, swiperight, swipetop, swipebottom`, you will be notified when the user taps, swipes or touches with finger or mouse the element. If you listen to the `resize` event, you will be notified whenever the element's boundaries are changed.
458 | * unlisten(eventType) - removes event listener by type.
459 | * getAttributeValue(attributeName, type) - gets the attribute's typed value.
460 | * setAttributeValue(attributeName, value, type) - sets the attribute's value by using a typed value.
461 |
462 | By invoking `Smart.Utilities.Extend(element)` you can extend any element with the above utility functions.
463 |
464 | In order to add a custom utility class, you can use `Smart.Utilities.Assign(classDefinition)`.
465 |
466 | ```javascript
467 | Smart.Utilities.Assign('defaultNumericProcessor', class defaultNumericProcessor {
468 | }
469 | ```
470 |
471 | To access that class, you can use `Smart.Utilities.defaultNumericProcessor`.
472 |
473 | ```*if and *items template directives.```
474 |
475 | If in the Template's definition, we have a HTMLTemplateElement, we can use these directives to insert HTML.
476 |
477 | * *if - Conditionally includes a template defaultd on the value of a property.
478 | * *items - Repeating a template by using each item of an iterable as that template's context.
479 | * templateAttached - function called when the HTMLTemplateElement is attahed to the DOM.
480 | * templateDetached - function called when the HTMLTemplateElement is detached from the DOM.
481 | * refreshTemplate - you can use this function to re-evaluate and refresh the HTMLTemplateElement.
482 |
483 | The below example creates a custom element called ```smart-test```. Within its template, the *if and *items directives are used. When the value of a property called ```condition``` is set to true, we render all items contained in the ```source``` property. When the value is set to false, we render again all items, but by using INPUT tags.
484 |
485 | ```
486 |
487 |
488 |
489 |
490 |
491 |
583 |
584 |
585 |
586 |
587 |
588 |
589 | ```
590 | ## Events
591 |
592 | The `listeners` object allows you to add and map events to event handlers.
593 |
594 | In the below example, the `listeners` object defines that a method called `_clickHandler` is called when the element is clicked. To listen to an event of an element from the template, you can use `nodeId.eventName` like `checkboxInput.click:_clickHandler`.
595 |
596 | ```javascript
597 | /**
598 | * CheckBox custom element.
599 | */
600 | Smart('smart-checkbox', class CheckBox extends Smart.ToggleButton {
601 | // CheckBox's properties.
602 | static get properties() {
603 | return {
604 | 'enableContainerClick': {
605 | value: true,
606 | type: 'boolean'
607 | }
608 | };
609 | }
610 |
611 | /** Checkbox's Html template. */
612 | template() {
613 | return `
614 |
615 |
616 |
617 |
`;
618 | }
619 |
620 | static get listeners() {
621 | return {
622 | 'click': '_clickHandler'
623 | };
624 | }
625 |
626 | /** Called when the element is ready. Used for one-time configuration of the Checkbox. */
627 | ready() {
628 | }
629 |
630 | /** Changes the check state wneh widget container is clicked. */
631 | _clickHandler(event) {
632 | const that = this;
633 |
634 | if (that.disabled) {
635 | return;
636 | }
637 |
638 | const isInputClicked = event.target === that.$.checkboxInput;
639 |
640 | if ((that.enableContainerClick === true && !isInputClicked) || isInputClicked) {
641 | that._changeCheckState('pointer');
642 | that.focus();
643 | }
644 | }
645 | });
646 |
647 | ```
648 | Binding to events within the Element's template.
649 | ```javascript
650 | Smart('my-element', class MyElement extends Smart.BaseElement {
651 | static get properties() {
652 | return {
653 | 'check': {
654 | type: 'boolean'
655 | }
656 | };
657 | }
658 |
659 | template() {
660 | return '';
661 | }
662 |
663 | _changeHandler() {
664 | alert('Checkbox State Changed');
665 | }
666 | });
667 | ```
668 |
669 | By using the utility functions described in the previous section, you can dynamically add and remove event listeners.
670 |
671 | ## Data Context
672 |
673 | The Data Context functionality of Smart Custom Element enables:
674 |
675 | * Dependency tracking - automatically updates parts of UI whenever a data model changes.
676 | * Declarative bindings - a way to connect parts of UI to a data model.
677 |
678 | The DataContext can be applied in two ways - by calling a method called ```applyDataContext``` or by setting a ```data-context``` attribute in the element's definition pointing to a DataModel object.
679 |
680 | The following example demonstrates how to use the ```DataContext``` feature.
681 |
682 | ```html
683 |
684 |
685 |
686 |
687 |
688 |
689 |
690 |
773 |
774 |
775 |
776 |
777 |
778 |
779 |