Skip to content

Instantly share code, notes, and snippets.

@m0jimo
Last active December 23, 2021 09:10
Show Gist options
  • Save m0jimo/ee298c7b8474599962d13e0938481824 to your computer and use it in GitHub Desktop.
Save m0jimo/ee298c7b8474599962d13e0938481824 to your computer and use it in GitHub Desktop.
Js functions which can be handy I don't want to loose.

Great Open Source projects:

IDE:

Discord channels:

Other SW and products:

  • ActivePresenter - Authorware for screen recording/editting and creating an elearning content
  • iTutor - Czech LMS for creating tests and hosting eLearning content developed by Kontis

Thanks to all great people who helped me from the communities above. I'm happy I could be with Quasar and Tauri projects from the beginning mostly as a user and in some cases as a contributer. Please, consider to support them on GitHub, too.

Javascript functions

Examples are copied from Vue components or .js files.

String to function

Eval and Function are devils but for converting string back to Javascript function there is no other way. Use case: convert string to function passing a context to eval

import {isNumber} from "quasar/src/utils/is";
// to acces the isNumber in string/function use this.isNumber inside a string

strToFc(str) {
 const strAsFc = this.evalInContext(str, {isNumber});
 console.log(strAsFc);
},
evalInContext(str, context) {
  // reset the previous error state
  this.error = null; 
  // passing error for the output from try catch part
  const me = this;
  // eslint-disable-next-line func-names
  return function () {
    try {
    // eslint-disable-next-line
      return eval(str);
    } catch (e) {
      me.error = e;
    }
    return null;
    // pass context
  }.call(context);
}

Create a DOM object

When working with Sharepoint spfx or for any other cases where using js frameworks is not necessery, simple function for creating a DOM object can be handy.

How to use it:

// ...
imgDom = dom.el("div", {style: `background:url(${data.Image}) no-repeat bottom right;`});
const adom = dom.el("a", aObj, [dom.el("div", {class: "gt-heading", title: title}, data.Title), imgDom]);
adom.addEventListener("click", () => {});
// ...
Click to expand module dom.js
const setNodeAttribute = (node, attribute, value) => {
 if (attribute === "class")
   node.className = value;
 else if (attribute === "checked")
   node.defaultChecked = value;
 else if (attribute === "for")
   node.htmlFor = value;
 else if (attribute === "style")
   node.style.cssText = value;
 else
   node.setAttribute(attribute, value);
};

const el = (name, attributes = {}, ...children) => {
 const node = document.createElement(name);
 if (attributes) {
   for (const att in attributes) {
     if (Object.prototype.hasOwnProperty.call(attributes, att)) {
       setNodeAttribute(node, att, attributes[att]);
     }
   }
 }
 const fragment = document.createDocumentFragment();
 children.forEach((child) => {
   if (typeof child === 'string') {
     const elem = document.createElement("div");
     elem.innerHTML = child;
     child = elem;
   }
   if (Array.isArray(child)) {
     child.forEach((ch) => {
       if (ch) {
         fragment.appendChild(ch);
       }
     });
   } else {
     if (child) {
       fragment.appendChild(child);
     }
   }
 });

 node.appendChild(fragment);
 return node;
};

export default {
 el
};

Manage hyperlinks in Sharepoint (spfx, .ts)

(<any>Object).assign(aObj, {
      href: "#",
      "data-interception": "off",
      rel: "noopener noreferrer"
    });

Copy To Clipboard with TypeScript

TypeScript usage for clipboard.writeText. Credit to: glebm #26728

// Type declarations for Clipboard API
// https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
interface Clipboard {
  writeText(newClipText: string): Promise<void>;
}
interface NavigatorClipboard {
  // Only available in a secure context.
  readonly clipboard?: Clipboard;
}

interface NavigatorExtended extends NavigatorClipboard {
}

const copyToClipboard = (str) => {
  return (navigator as NavigatorExtended).clipboard.writeText(str);
};

Reset Vuex to initial state

Example from Vue and Vuex state managment.

// store/index.js
const initState = () => {
  return {
    table: [],
    EXE_LOADED: false,
    EXE_CHANGED: false
  };
};

const store = new Vuex.Store({
  state: {
    envSettings: {}, // keep this part unchanged after recovering initState
    ...initState()
  },
  getters: {},
  mutations: {
   INIT_STATE(state, payload) {
      const st = initState();
      Object.keys(st).forEach((key) => {
        state[key] = st[key];
      });
    }
  },
  actions: {
   initState({ commit }, payload) {
      commit("INIT_STATE");
   },
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment