Sharing variables between functions in javascript - javascript

if this question is not clear, let me know and I will exapand on it. Not great with JS.
I have a js file. let's call it jsFile1.js in which I have two methods. Method1 is being called from another file (anotherJsFile.js) and that call sends a variable to the Method1 in jsFile1.js.
Now I want my second method, Method2, which is being called from inside jsFile1.js to also be able to use the variable sent from anotherJsFile to method 1.
Have tried using id's and set value etc but it won't work. Any suggestions? Presume I have to store const tmp in the config or init and then access it from the Method2?
File1
Method1(item, table) {
//item is a marked item from the table, table contains all entries
const tmp = {table, id: "tmpTable"};
}
Method2() {
const data = this.$$("tmpTable").getValues();
}
config() {
const Method2Button = {
view:"button",
label:"Method2",
click: () => this.Method2()
}}

Just write a method that takes an integer and import the class in you constructor
File1.js
private test: any
Method1(item, table) {
const tmp = {table, id: "tmpTable"};
this.test = tmp
}
Method2() {
return this.test.id //.getValues() ??
// return this.class.getValues(this.test.id)
}
config() {
const Method2Button = {
view:"button",
label:"Method2",
click: () => this.Method2()
}}

Related

Trying to get a value from a custom store Svelte

i want to ask something, i have a custom store like
const BlaBla = (Data) => {
const { subscribe, set, update } = writable(Data);
return {
subscribe,
update,
set,
setData: (NewData) => {
set(NewData)
},
getData: () => {
return <<<<<<< "Here lies the problem, how i can get the "newData"?."
}
}
}
i will explaying the scenario, im creating a script for a fivem server and im using svelte, i create a store that get a Vehicle with some properties like Name, Last Name, Plate and bla bla, i create the setData(Vehicle) and pass a set(Vehicle) then in another method i want to "get" the plate only, one solution i did was creating a variable in the scope and instead of a set i did an update like this
const VehicleStore = (Vehicle) => {
let Data = {} //Variable inside the scope
const { subscribe, set, update } = writable(Vehicle);
return {
subscribe,
update,
set,
setData: (NewData) => {
update((s) => {
s = NewData
Data = s
return s
})
},
getData: () => {
return Data.Plate
}
}
}
i don't know if this is the actual solution, i think im missing something
Svelte exports a get function that can be used to resolve the value of a store once (it is syntactic sugar around subscribe).
So first you have to get the value of the store, then you can access its property:
import { get } from 'svelte/store';
// ...
const store = writable(Data);
const { subscribe, set, update } = store;
// ...
return get(store).Plate
Note that accessing data like this will not be reactive because there is no persistent subscription to the store. You are generally not meant to use stores like that.
Instead you usually would use the store in a component's markup using auto subscriptions via $:
$VehicleStore.Plate

Vue3 Multiple Instances of Composition API Data Store

Simplifying a real-life situation...
Let's say I have a webapp with two columns. The same component used in both columns. The functionality uses data storage and functions created in a separate composition api js file, made available to the component by importing and then provide/inject. Works great.
But is there a way to write the js file with the composition api once, and then create multiple instances when it's imported to the Vue app? That way a separate instance can be sent to each component and they won't share the same data object. I know if you import the same file with multiple names...
import instanceone from "path";
import instancetwo from "path";
...they'll both share the same objects because it's importing the same file as two names, not two instances of the file.
Is there any way to achieve something like this? I'm interested in any setup that would achieve the end goal (not needing two copies of the file to achieve two independent usages). I took a flyer and thought maybe creating a single file that exports objects and functions, then two files that each import the appropriate pieces of that single file, and then let Vue import those two files might work...but nope, not so much.
Obviously there are plenty of other ways to do this, but I want to explore this possibility first. Preferably without making use of Vuex.
Thank you!
the following is one of the way to achieve this
/* composable_module.js */
import { ref, computed } from 'vue';
export const shared_var_1 = ref(0);
export const shared_var_2 = ref(0);
export function composable_variables() {
// will return separate instance of variables for each call
const var1 = ref(0);
const comp_var1 = computed(() => var1.value + shared_var_1.value);
// comp_var1 updates value when either var1 or shared_var_1 value gets updated
return { var1, comp_var1 };
}
usage as following
/* component_1.vue */
import { shared_var_1, shared_var_2, composable_variables } from 'composable_module.js';
/* other things needed for component or any file */
setup() {
const { var1, comp_var1 } = composable_variables();
/*
Do what you want to do with
shared_var_1, shared_var_2, var1, comp_var1
*/
// return whatever you wanted to use in template
return { shared_var_1, shared_var_2, var1, comp_var1 }
}
Here shared_var_1, shared_var_2 will act as vuex store values
and var1, comp_var1 will be separate for each function call
so can be used in multiple components as separate variable sharing common functionality but not value.
Within your 'path' composable you could define two states, then call the relevant state with something like:
const { getItem1, getItem2, setItem1, setItem2 } = (whichInstance) ? instanceOne : instanceTwo
You just need to define your whichInstance condition to determine which instance you want.
Your composable could be something like:
const stateOne = reactive({
item1: true,
item2: 1
})
const stateTwo = reactive({
item1: false,
item2: 2
})
export function instanceOne() {
let stateRef = toRefs(stateOne)
/* Getters */
const getItem1 = () => {
return stateRef.item1
}
const getItem2 = () => {
return stateRef.item2
}
/* Mutations */
const setItem1 = (value) => {
stateRef.item1.value = value
}
const setItem2 = (value) => {
stateRef.item2.value = value
}
return {
state: toRefs(stateOne),
getItem1,
getItem2,
setItem1,
setItem2
}
}
export function instanceTwo() {
let stateRef = toRefs(stateTwo)
/* Getters */
const getItem1 = () => {
return stateRef.item1
}
const getItem2 = () => {
return stateRef.item2
}
/* Mutations */
const setItem1 = (value) => {
stateRef.item1.value = value
}
const setItem2 = (value) => {
stateRef.item2.value = value
}
return {
state: toRefs(stateTwo),
getItem1,
getItem2,
setItem1,
setItem2
}
}
})

Using a function defined inside an exports function, from another file

I have some code like this in a file helperFunctions.js:
exports helperFunctions = () => {
const functionA = async(args) => {
console.log(args);
};
const functionB = async(args) => {
functionA(myArg);
};
}
How can I call functionA and functionB from a separate file altogether, say, main.js?
I've tried:
import { helperFunctions } from './helperFunctions';
//...some code
helperFunctions.functionA('hello');
// OR
functionA('hello');
The specific error is:
TypeError: _helperFunctions.helperFunctions.functionA is not a function
and when trying the second solution, it's:
ReferenceError: functionA is not defined
I'm trying to avoid importing literally every single function I'm using (by way of exporting every single function I'm using). I'd like to do something like helperFunctions.function for the functions I need.
It really need to be a function? You could export an Object:
// helperFunctions.js
let helperFunctions = {
functionA: async (args) => {
console.log(args);
},
functionB: async (args) => {
functionA(myArg);
}
}
exports helperFunctions;

Nightwatch(PageObject) access elements from different page object

Is there a way to access elements defined in one page object file from another page object file?
Example:
If we need to access '#usernameInput' from LoginPage.ts file, do we need to duplicate it from HomePage.ts ? Is there any other way?
HomePage.ts
const page: PageObject = {
url: ...,
commands: [
enterUsername: (query: string) => {
return this
.waitForElementVisible('#usernameInput')
}],
elements: {
usernameInput: {
locateStrategy: 'xpath',
selector: '//input[#name="Username"]',
}
};
LoginPage.js
const page: PageObject = {
url: ...,
commands: [
enterUsername: (query: string) => {
return this
.waitForElementVisible('#usernameInput')
}],
elements: {}
};
You can access one page object from another by using this.api.page.pageObjectName.
In your example you would just do
const loginPage = this.api.page.loginPage();
And then to get the usernameInput element you can just do this
const usernameInput = loginPage.elements.usernameInput.selector;
So your enterUsername function should look something like the following
enterUsername: (query: string) => {
const loginPage = this.api.page.loginPage();
const usernameInput = loginPage.elements.usernameInput.selector;
return this
.waitForElementVisible(usernameInput)
.setValue(usernameInput, query);
}
Use LocalStoreage to keep your data and access in all the page using Javascript or Jquery
Set your Object
localStorage.setItem("PortPlans", PortPlans);
call your localstorage in another page
var PortPlans = localStorage.getItem("PortPlans");
console.log(PortPlans);

Vue 2.0, where to place local functions

Where do you correctly place local functions in vue 2.x?
I could just place them in the "methods" object, but I'd like them to be completely local to the instance if thats possible.
Sort of like this in Plain JS :
window._global = (function () {
function _secretInsideFunct(){
return "FooBar";
}
var __localObject = {
outsideFunct : function () {
return _secretInsideFunct();
}
}
return __localObject;
}());
..where _global._secretInsideFunct() wouldnt be accessible anywhere else but from inside the _global object.
In this specific case I want to make a function that creates an array object if it doesn't exist.. Something like:
function CreateOrSet (workArray, itemName, itemValue ){
var salaryRow = self.Status.Rows.find(r => r.recordID == itemName);
if (!salaryRow) {
salaryRow = { recordID: itemName, recordAmount: 0, recordName: "Løn" };
self.Status.Rows.push(salaryRow);
}
salaryRow.recordAmount = itemValue ;
}
..but a general approach for these cases is better :)
Now this function doesn't looks like a utility or helper function, but relate to a state, Status.Rows. If I were you, I will define it as close as to the state or the module that the state being used.
If the state will be used across the app, maybe I will define it in entry file, index.js or app.vue.
Or If you are using vuex, you can define it as an vuex action. So you may do something like this:
const store = new Vuex.Store({
state: {
status: {
rows: []
},
mutations: {
pushRow (state, salaryRow) {
state.status.rows.push(salaryRow)
},
changeAmount (state, id, amount) {
const salaryRow = state.status.Rows.find(r => r.recordID === id)
salaryRow.recordAmount = amount
}
},
actions: {
createRow (context, itemName) {
const salaryRow = { recordID: itemName, recordAmount: 0, recordName: "Løn" };
context.commit('pushRow', salaryRow)
}
}
})
You can put all of the code to a single action, it is just an idea, how you organize your code depend on your needs.

Categories

Resources