Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function(ajax) {
- 'use strict';
- const ON_TEXT = 'On';
- const OFF_TEXT = 'Off';
- const LOADING_TEXT = 'loading';
- const RESOURCE_URL = '/ze-api';
- class Toggle {
- constructor(wrapper) {
- this.handleToggle = this.handleToggle.bind(this);
- this.handleSuccess = this.handleSuccess.bind(this);
- this.handleFailure = this.handleFailure.bind(this);
- this.receiveDefaultValue = this.receiveDefaultValue.bind(this);
- this.wrapper = wrapper;
- this.onText = this.wrapper.getAttribute('data-toggle-on') || ON_TEXT;
- this.offText = this.wrapper.getAttribute('data-toggle-off') || OFF_TEXT;
- this.isActive = false;
- this.toggle = document.createElement('a');
- this.toggle.className = this.toggle.className += ' toggle-trigger loading';
- this.toggle.href = '#';
- this.toggle.text = LOADING_TEXT;
- this.wrapper.appendChild(this.toggle);
- this.getDefaultValue();
- }
- getDefaultValue() {
- ajax({
- method: 'get',
- url: RESOURCE_URL,
- data: {
- id: this.wrapper.getAttribute('data-toggle-id'),
- tid: 1
- },
- dataType: 'json',
- success: this.receiveDefaultValue,
- error: this.handleFailure
- });
- }
- receiveDefaultValue(data) {
- this.toggle.addEventListener('click', this.handleToggle);
- this.isActive = (data.result && data.result == true);
- this.toggle.text = this.isActive == true ? this.offText : this.onText;
- this.toggle.className = this.toggle.className.replace(' loading', '');
- }
- handleToggle(e) {
- this.isActive = this.isActive == true ? false : true;
- this.toggle.text = this.isActive == true ? this.offText : this.onText;
- if (this.toggle.className.indexOf('loading') < 0) {
- this.toggle.className = this.toggle.className += ' loading';
- ajax({
- method: 'post',
- url: RESOURCE_URL,
- data: {
- id: this.wrapper.getAttribute('data-toggle-id'),
- toggleState: this.isActive
- },
- success: this.handleSuccess,
- error: this.handleFailure
- });
- }
- e.preventDefault();
- }
- handleSuccess() {
- this.toggle.className = this.toggle.className.replace(' loading', '');
- }
- handleFailure() {
- this.toggle.className = this.toggle.className.replace(' loading', '');
- this.toggle.className = this.toggle.className += ' error';
- }
- }
- const init = function() {
- var toggles = document.getElementsByClassName('toggle');
- for (var i = 0; i < toggles.length; i ++) {
- var toggle = toggles.item(i);
- if (toggle.className.indexOf('toggle-processed') < 0) {
- toggle.className += toggles.item(i).className += ' toggle-processed';
- new Toggle(toggle);
- }
- }
- }
- window.addEventListener('load', init);
- })(jQuery.ajax);
Add Comment
Please, Sign In to add comment