/ Gists

Gists

On gists

4 ways to dynamically execute JavaScript code on the front end

JavaScript

HOW.JS #

// https://medium.com/@bestowensss/4-ways-to-dynamically-execute-javascript-code-on-the-front-end-01648b4f527a

// 1
/*
Synchronous execution;
The execution context is the current scope .
*/
let a = 1;
function test() {
  let a = 2;
  eval('console.log(a)'); // 2
}
test();


// 2
/*
Synchronous execution;
The execution environment is the global scope .
*/
let a = 1;
function test() {
  let a = 2;
  let fn = new Function('console.log(a)');
  fn(); // 1
}
test();


// 3
// 2
/*
Asynchronous execution;
The execution environment is the global scope .
*/
let a = 1;
function test() {
  let a = 2;
  setTimeout('console.log(a)', 1000); // 1
}
test();


//4 
/*
Synchronous execution;
The execution environment is the global scope .
*/
var a = 1;
let script = document.createElement('script');
script.textContent = 'console.log(1)';
document.body.appendChild(script); // 1

On gists

Dynamic component (h or :is with v-bind)

Vue.js

Dynamic.vue #

<!-- 1 -->
<component
    v-if="transport?.image"
    :is="typeof transport.image === 'object' ? 'aw-img' : 'img'"
    v-bind="
      typeof transport.image === 'object'
        ? { image: transport.image, size: 'eop-icon', style: 'max-width: 40px' }
        : { src: transport.image, size: 'eop-icon', style: 'max-width: 40px' }
    "
  />
  
  
  <!-- 2 h render -->
 const transportImage = computed(() => {
      if (!props.transport?.image) return null

      if (typeof props.transport.image === 'object') {
        return h(resolveComponent('aw-img'), {
          image: props.transport.image,
          size: 'eop-icon',
          style: 'max-width: 40px'
        })
      } else {
        return h('img', {
          src: props.transport.image,
          size: 'eop-icon',
          style: 'max-width: 40px'
        })
      }
    })

On gists

Token for JWT / Bearer

PHP

token-fn.php #

<?php

$currentTime = time();
$timeWindow = 500; // token expiration
$expectedToken = hash_hmac('sha256', $currentTime - ($currentTime % $timeWindow), 'OUR_ANY_SECRET');

// echo hash_equals($expectedToken, $anyTokenFromGetorPost);

On gists

V-memo

Vue.js

v-memo.js #

// https://learnvue.co/articles/v-once-v-memo

<script setup>
import { ref } from 'vue'

const subscribers = ref(4000)
const views = ref(10000)
const likes = ref(3000)
</script>
<template>
  <div>
    <div v-memo="[subscribers]">
      <p>Subscribers: {{ subscribers }}</p>
      <p>Views: {{ views }}</p>
      <p>Likes: {{ likes }}</p>
    </div>
    <button @click="subscribers++">Subscribers++</button>
    <button @click="views++">Views++</button>
    <button @click="likes++">Likes++</button>
    <div>
      <p>Current state:</p>
      <p>Subscribers: {{ subscribers }}</p>
      <p>Views: {{ views }}</p>
      <p>Likes: {{ likes }}</p>
    </div>
  </div>
</template>

On gists

Advanced Patterns: Mixins and Composition

JavaScript-OOP JavaScript

composition.js #

// https://medium.com/@genildocs/mastering-object-oriented-programming-in-javascript-from-zero-to-hero-c718c3182eba

// Mixin for logging functionality
const LoggerMixin = {
  log(message) {
    console.log(`[${this.constructor.name}] ${message}`);
  },

  logError(error) {
    console.error(`[${this.constructor.name}] ERROR: ${error}`);
  }
};

// Mixin for validation
const ValidatorMixin = {
  validate(data, rules) {
    for (const [field, rule] of Object.entries(rules)) {
      if (!rule(data[field])) {
        return { valid: false, field };
      }
    }
    return { valid: true };
  }
};

class UserService {
  constructor() {
    // Apply mixins
    Object.assign(this, LoggerMixin, ValidatorMixin);
  }

On gists

Reactivity in composables

Popular ⭐ Vue.js

App.vue #

<template>
  <TheBase :state="state" />
</template>


<script setup>
import { ref } from 'vue'
import TheBase from './TheBase.vue'


const state = ref(111)

setTimeout(() => {
  state.value = 222
}, 2000)
</script>

On gists

3 Vanilla-Lite DOM Patterns That Achieve jQuery’s Ease

JavaScript-OOP JavaScript

1.js #

// Pattern 1 — Bind Helper

export function S(selector) {
  const nodes = document.querySelectorAll(selector);
  nodes.forEach(bindAll); // Bind helpers to node(s)

  return nodes.length > 1 ? nodes : nodes[0]; // native node(s) returned
}

export function C(tag) {
  const node = document.createElement(tag);
  return bindAll(node); // Bind helpers to node(s)
}

function bindAll(node) {
  node.addClass = addClass.bind(node);
  node.attr = attr.bind(node);

  return node;
}

//--- Extension functions ---//
function addClass(...cls)   {
  this.classList.add(...cls);
  return this;
}

function attr(key, val) {
  if (val !== undefined) {
    this.setAttribute(key, val);
    return this; 
  }

  return this.getAttribute(key);
}


// Usage:
import { S, C } from './helper.js';

const btn = C('button').addClass('btn', 'primary').attr('type', 'submit');
btn.click(); // native method

S('.card').forEach(el => el.addClass('highlight').attr('data-live', '1'));

On gists

Slots drilling

Popular ⭐ Vue.js

better-way.vue #

<!-- Parent -->
  <script setup>
    provide('transportFree', useSlots().transportfree)  // slot existuje i kdyz ho vubec nepouziju v komponente, ve smyslu <slot name="transportfree" />, staci zvenci <template #transportfree>content</template>
 </script>
 
 <!-- Any Grand-Grand-Child -->
 <script setup>
    const transportFree = inject('transportFree') // or with params   <component :is="transportFree?.({ someProp: 123 })" />
 </script>
 <template>
    <component :is="transportFree" />
 </template>

On gists

bete

bete #

_

On gists

Starting style

CSS CSS trick

style.css #

/* https://jsbin.com/fayirefaqu/2/edit?html,css,js,output */


.modal {
  /* Hidden state */
  display: none;
  opacity: 1;
}

.modal.open {
  display: block;
  /* Regular transition works now */
  transition: opacity 300ms;
  opacity: 1;
}

/* Define starting styles when modal becomes displayed */
@starting-style {
  .modal.open {
    opacity: 0;
  }
}