How to create local helpers to tidy up Vue components - javascript

I have a Vue component that does a number of complex tasks in mounted(). These tasks include for example, initializing Bootstrap Date Pickers, Time Pickers, and Typeaheads.
At the moment all of this initialization code is in my mounted() method. In order to understand what's going on, the developer has to read through the code comments.
Ideally I would move sections of code to their own methods, and only have method calls in mounted(), something such as:
mounted () {
this.helpers.initDatePickers();
this.helpers.initTimePickers();
this.helpers.initTypeaheads();
}
How can I achieve this? I realise that I can put them in the methods object, but I would prefer to leave that for methods which can be accessed via declarations in templates.
Note that I am not asking how to share helper functions across components (or globally). I am merely asking how to create local functions in their own space, in order to clean up some longer methods.

You could create a mixin module which has generic initialization.
// DatePickerMixin.js
import whatever from 'specific-date-picker-stuff';
export default {
methods: {
initDatePickers() {
// initialization here
}
}
}
Then your component just uses the mixin modules.
<script>
import DatePickerMixin from './mixins/DatePickerMixin';
import TimePickersMixin from './mixins/TimePickersMixin';
export default {
mixins: [
DatePickerMixin,
TimePickersMixin
],
data() {/* ... */},
// etc.
}
</script>
You could wrap all of these in the same mixin as well.
And if you don't want to always set the mixins, there's global mixin.
import DatePickerMixin from './mixins/DatePickerMixin';
Vue.mixin(DatePickerMixin);
Use global mixins sparsely and carefully, because it affects every
single Vue instance created, including third party components.

As #EmileBergeron said, mixins are a good solution. You can also create plugins, which so happen to encompass mixins as well but much more. They allow you to extend the Vue constructor or add instances/methods directly to the Vue prototype.
Section on plugins from the documentation
MyPlugin.install = function (Vue, options) {
// 1. add global method or property
Vue.myGlobalMethod = function () {
// something logic ...
}
// 2. add a global asset
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// something logic ...
}
...
})
// 3. inject some component options
Vue.mixin({
created: function () {
// something logic ...
}
...
})
// 4. add an instance method
Vue.prototype.$myMethod = function (methodOptions) {
// something logic ...
}
}
Using your plugin is done by:
// calls `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
// pass options to your plugin
Vue.use(MyPlugin, { someOption: true })
Here's a small plugin I recycle exposing various string functions in the pluralize library:
import {plural, singular, camelCase} from 'pluralize'
PluralizePlugin.install = function (Vue, options) {
Vue.plural = plural
Vue.singular = singular
Vue.camelCase = camelCase
}
With it you can use this.singular(str), this.plural(str), etc. throughout your components. Pretty simple but convenient.

Related

Custom hook that only returns helper functions

I made a custom hook that only returns helper functions. Nowhere in the custom hook do I use another hook (useState, useEffect...)
Example:
import backend from '../lib/backend';
import axios, { AxiosError } from 'axios';
interface PresignedData {
fields: any;
url: string;
key: string;
}
type Resource = 'users' | 'events';
function useBucket() {
const uploadViaPresignedPost = async function (
resource: Resource,
file: File
) {
...
};
const buildImageUrl = function (key: string) {
return `${process.env.NEXT_PUBLIC_S3_BUCKET_DOMAIN}/${key}`;
};
return { uploadViaPresignedPost, buildImageUrl };
}
export default useBucket;
Is this common practice? Or would it be better to create a class with static methods? export helper functions from separate file? What is best practice?
Using a class for this wouldn't make all that much sense because a class is meant for when you need to tie together data associated with an instance with methods that can operate on that data. If there's no data associated with an instance - if the class never has new called on it - then there's not much point to a class in the first place. A few plain functions or a plain object with functions in it would make more sense than a class.
Your current approach of a custom hook that doesn't use any other hooks inside it seems a bit weird, but it's not forbidden. Feel free to use that approach if you want. Using a custom hook has an added benefit that if you later decide to change the logic and, for example, feel the desire to add a useState or useEffect or something to the custom hook, it's trivial to add them into the custom hook. In contrast, if you used anything other than a custom hook and later found that you needed to add something that required hook logic, you would not be able to without first refactoring everything back into a custom hook again.

Undertanding JavaScript methods

I am pretty new to JavaScript, coming from a Java background. I was just playing around with the NodeJS ("type": "module") Express framework but got between two types of ways for writing the methods in JS.
Below are the examples (check comments inline).
Type 1:
main.js
const method1 = () => {
...
method2();
...
};
const method2 = () => {
// this is not exported, so it works as a private method and won't be accessible in other JS files
...
};
.
.
.
// likewise there can be many other methods here
export { method1 }; // export other methods as well
Then, I can use the method1 (cannot use method2 as it is not exported) in any other JS file like below:
test.js
import { method1 } from './main.js';
method1();
Type 2:
main.js
class Main {
method1() {
...
method2();
...
}
#method2() {
// this is a private method, so won't be accessible outside of this class
...
}
// likewise other methods here
}
const main = new Main();
export default main;
Then, I can use this class instance in any other JS file like below:
test.js
import main from './main.js';
main.method1();
I want to know what is the difference between these two, when to use which, and which is better.
Both approaches work fine, but Type 2 is somewhat weird because you're using a class only to keep something from being exported.
Classes are usually used to group together data (properties on the instance of the class) with methods that operate on that data. For a silly example:
class NumberMultiplier {
constructor(num) {
this.num = num;
}
multiply(mult) {
return this.num * mult;
}
}
const n = new NumberMultiplier(5);
console.log(n.multiply(10));
Above, there is data (this.num), and there's also a method that operates on the data (multiply).
But in your case, you don't look to have instance data - you only want to group functions together, there's not really a reason to use a class. You can consider defining the functions individually - as you did in the first snippet - or you could use a plain object that gets exported, with only the properties you need:
const method2 = () => {
};
export default {
method1() {
method2();
}
};
If you do have persistent data and want to put it on the class instance, using a class and # private methods is a possibility (creating a single instance with new and then exporting that instance is an example of a singleton).
A potential issue to be aware of is that if you use export default with an object, there's no way to extract a single property of the export when importing in a single line. That is, if you only have a default export, you can't do something like
import { method1 } from './main.js'.default;
You could only do
import theObj from './main.js';
const { method1 } = theObj;
which some would consider to look a bit ugly. Having independent named exports can make it a bit easier for the consumers of a module to import only what they need into standalone identifiers, in a single line.
Classes in JS, unlike your familiarity in Java, are rarely used when not explicitly necessary. Nevertheless, there are situations where OOP in JS could be very useful.
Basically, the first method (Type 1) is what you're going to be using/seeing 99% of the time if you're doing just general JS programming such as front-end websites or apps.
If you're i.e. making a game however, you could use OOP to have better control over the different characters/object in your game.
In terms of back-end or on an infrastructural level, it really depends. You could perfectly use classes (Type 2) if you're following the MVC design pattern, but is again optional.
In the end, it comes down to your own design choice(s). You could go for FP (T1) or OOP (T2) whenever you like in JS, although there are some 'industry standards' for certain scenarios to decide when to use which.
It actually depends on what you are exporting. The type 1 is more appropriate if you export only one or a few objects. With type 1, you can export any primitive type variables or objects and can be used straightaway in the main.js.
However, if you want to export many objects and/or variables, then type 2 makes sense. With type 2, all exports are stored in an object, so you have to access them using this object.
Performance-wise both are same.

How to use javaScript file as Higher Order wrapper for other JavaScript File

I want to ask, as in react we have HOC (Higher order components) where we pass components that modify it and then return modified Component for use
can we do same in javaScript?
for Example
// index1.js
// this is file where i am importing all the folder modules and exporting them
export { methodA, methodB } from './xyzAB'
export { methodC, methodD } from './xyzCD'
i am importing this file in another folder like this
import * as allMethods from './modules'
// this allows me to use this syntax
allMethods.methodA()
allMethods.methodB()
this is working fine, but i am looking for this kind of wrapper
// index2.js
// this is another file somewhere else where i want to use index1.js exported methods
import * as allMethods from './modules/xyz'
import anotherMethod from './somewhere/xyz'
// here i want customize some of `allMethods` functions and export them as new object
//which contains modifed version of default `index1.js` methods
allMethods.methodA = allMethods.methodA( anotherMethod ) // this is example of modified as HO Method
export default allMethods
My Above example may seem confusing,
why i am looking for such solution, i have set of utilities which i am trying to make them as library and use them in multiple projects,
now some of utils are dependent on main project related things, so instead of giving my utilities hard coded reference to their dependencies,
i want to pass different dependencies for different methods through my higher order method or configuration file,
so that each new project pass its dependent utilities from their config or higher order wrapper file as example shown above
I hope i was able to clear my question,
Few things which i tried,
i tried importing all modules in file which i count as wrapper file
in that if i try to use any module that returns webpack error as undefined method, due to methods not loaded fully until few seconds, i tried setTimeOut, that works fine, but this is not valid way of managing thing,
then i tried some async way, i used dynamic import() which returns promise, i used async/await syntax, and also used .then syntax but couldn't extract data and save it as variable (i may be doing something wrong at this step but i was totally failed) but this was only available with in promise or async await scope,
there were also other steps tried,
i am hoping i could find some neater syntax like below
import * as F from '../../core/lib/functions'
import { getModel } from '../entities'
F.getKeys = F.getKeys( getModel )
export default F
any suggestion is welcome
I think what you're looking for is some sort of currying or factory-like pattern.
There is no such thing as higher order modules but since JavaScript support higher order functions that is what you should use.
Just as a reminder, a higher order component is any component that takes a component as a parameter and returns another component. Similarly (simplified) a higher order function is one that takes a function as a parameter and returns a new function. (in reality all React components are more or less functions so thus why we are able to have higher order components).
The key thing is that you need to call a higher order function, not just import it (since again, there is no such thing as a higher order module). But this ties well into your idea of dependency injection.
I think, what you want is something like this in your utilities:
function a(dependency1, arg1, arg2) {}
function b(dependency2, arg1, arg2) {}
function createUtils(dependency1, dependency2) {
return {
a: a.bind(null, dependency1),
b: b.bind(null, dependency2)
}
}
This allows you to customize per project what dependency 1 and 2 are and the details for how they work (with some common interface). With the binding you don't have to pass that dependency in with every call to a function.
Then in one of your projects you'd set them up something like this:
import { createUtils} from 'utils';
import { dependency1, dependency2 } from 'somewhere' ;
const { a, b } = createUtils(dependency1, dependency2)
export { a, b };
You're not really doing any higher order function stuff, like I said this is more like a factory/dependency injection thing. Though bind is a higher order function (it takes the function it's called in and returns a new function with some arguments bound).
You can put place in createUtils for general modifications through another parameter with options. Or you can export smaller "factories" for each method that you want to be able to modify.
With that in mind you might to only export the raw functions from utils and use bind in your module setup code to bind the dependencies. I think bind is what you are missing. As well as that you have to create new functions to export, rather than modifying the imported functions. That also means that your imports in the rest of your code will come only from within your own module, not from the utils module.

Write Vue plugin with custom options

I'm trying to write a vue plugin with custom options. I followed the official vue guidelines (https://v2.vuejs.org/v2/guide/plugins.html) on doing so but can't find a way to define custom options. These options should be read by normal javascript which then exports an object that is used by a vue component.
My folder structure is like this:
/src
factory.js
CustomComponent.vue
factory.js
import Vue from "vue";
import ImgixClient from "imgix-core-js";
var imgixClient = new ImgixClient({
domain: CUSTOM_OPTION_URL <-- important bit
domain: Vue.prototype.$imgixBaseUrl //tried it like this
});
export { imgixClient };
I already tried to set this custom bit by utilizing Vue.prototype in the install method like this but can't seem to get it working
export function install(Vue, options) {
if (install.installed) return;
install.installed = true;
Vue.prototype.$imgixBaseUrl = options.baseUrl;
Vue.component("CustomComponent", component);
}
I'm afraid this isn't going to be the simple answer you might have been hoping for... there's a lot to unpick here.
Let's start with factory.js. That is not a factory. It's a singleton. Singletons have problems around dependencies, configuration and the timing of instantiation and that's precisely the problem you're hitting. More on that later.
Now let's take a look at the plugin. First up, these two lines:
if (install.installed) return;
install.installed = true;
That shouldn't be necessary. Vue already does this automatically and should ensure your plugin is only installed once. Perhaps this came from an old tutorial? Take a look at the source code for Vue.use, there's not a lot to it:
https://github.com/vuejs/vue/blob/4821149b8bbd4650b1d9c9c3cfbb539ac1e24589/src/core/global-api/use.js
Digging into the Vue source code is a really good habit to get into. Sometimes it will melt your mind but there are some bits, like this, that aren't particularly difficult to follow. Once you get used to it even the more opaque sections start to become a little clearer.
Back to the the plugin.
Vue.prototype.$imgixBaseUrl = options.baseUrl;
It is not clear why you are adding this to the prototype.
I'm going to assume you are already familiar with how JavaScript function prototypes work.
Component instances are actually instances of Vue. So any properties added to Vue.prototype will be inherited by your components with almost no overhead. Consider the following simple component:
<template>
<div #click="onClick">
{{ $imgixBaseUrl }}
</div>
</template>
<script>
export default {
methods: {
onClick () {
const url = this.$imgixBaseUrl
// ...
}
}
}
</script>
As $imgixBaseUrl is an inherited property it is available within onClick via this.$imgixBaseUrl. Further, templates resolve identifiers as properties of the current Vue instance, so {{ $imgixBaseUrl }} will also access this.$imgixBaseUrl.
However, if you don't need to access $imgixBaseUrl within a component then there is no need to put it on the Vue prototype. You might as well just dump it directly on Vue:
Vue.imgixBaseUrl = options.baseUrl;
In the code above I've ditched the $ as there's no longer a risk of colliding with component instance properties, which is what motivates the $ when using the prototype.
So, back to the core problem.
As I've already mentioned, singletons have major problems around creation timing and configuration. Vue has its own built-in solution for these 'do it once at the start' scenarios. That's what plugins are. However, the key feature is that plugins don't do anything until you call install, allowing you to control the timing.
The problem with your original code is that the contents of factory.js will run as soon as the file is imported. That will be before your plugin is installed, so Vue.prototype.$imgixBaseUrl won't have been set yet. The ImgixClient instance will be created immediately. It won't wait until something tries to use it. When Vue.prototype.$imgixBaseUrl is subsequently set to the correct value that won't have any effect, it's too late.
One way (though not necessarily the best way) to fix this would be to lazily instantiate ImgixClient. That might look something like this:
import Vue from "vue";
import ImgixClient from "imgix-core-js";
var imgixClient = null;
export function getClient () {
if (!imgixClient) {
imgixClient = new ImgixClient({
domain: Vue.prototype.$imgixBaseUrl
});
}
return imgixClient;
}
So long as nothing calls getClient() before the plugin is installed this should work. However, that's a big condition. It'd be easy to make the mistake of calling it too soon. Besides the temporal coupling that this creates there's also the much more direct coupling created by sharing the configuration via Vue. While the idea of having the ImgixClient instantiation code in its own little file makes perfect sense it only really stands up to scrutiny if it is independent of Vue.
Instead I'd probably just move the instantiation to within the plugin, something like this:
import ImgixClient from "imgix-core-js";
export default {
install (Vue, options) {
Vue.imgixClient = Vue.prototype.$imgixClient = new ImgixClient({
domain: options.baseUrl
});
Vue.component("CustomComponent", component);
}
}
I've made a few superficial changes, using a default export and wrapping the function in an object, but you can ignore those if you prefer the way you had it in the original code.
If the client is needed within a component it can be accessed via the property $imgixClient, inherited from the prototype. For any other code that needs access to the client it can either be passed from the component or (more likely) grabbed directly from Vue.imgixClient. If either of these use cases doesn't apply then you can remove the relevant section of the plugin.

Is it possible to create a global attach() handler for viewmodels?

I have a use case with Aurelia where I would like to have a handler run for every view that is attached. (It's an HTML5 polyfill for date and number inputs that would work via querySelector.) I realize that I could call this within every view that I create, but I'm wondering if there's a best practice to set this at a global level. (Note: This could probably be done with a router pipeline step, but all views may not be subject to that, such as views loaded via compose.)
I realize that this could potentially be dangerous, but is there a best practice to add global attached() and detached() handlers for views and viewmodels?
Edit: Looking here (https://github.com/aurelia/templating/blob/ee5b9d6742fddf3d163aee8face6e6a58ba1554c/src/view.js#L259) it looks as though it would be possible to add a hook for a global handler here that took a view as an argument, but I'd rather not have to change the framework code if possible.
My idea would be to create a base viewmodel class with an attached logic, which would contain globally required functionality.
Extended viewmodels could call super.attached() to execute global logic as needed.
You can find a demo here: https://gist.run/?id=fea4069d8a4361c4802c7c5d42105145
This can work with compose as well. I know, it isn't a completely automated solution but an opt-in method, so it would require a bit of additional work on all viewmodels.
Base class - used by all viewmodels
import { inject } from 'aurelia-framework';
#inject(Element)
export class BaseView {
constructor(element) {
this.element = element;
}
attached() {
// global logic goes here
}
}
Example viewmodel - actual implementation
import { BaseView } from './base-view';
import { inject } from 'aurelia-framework';
#inject(Element)
export class ExtendedView extends BaseView {
constructor(element) {
super(element);
}
attached() {
super.attached(); // global logic runs
}
}

Categories

Resources