Calling a Backend Function .jsw

Hello there friends!

I created 2 simple functions that open and close a menu. I’m trying to store those functions in the backend to then be able to call them on any page. Am I thinking this wrong? is there other way to define the functions globally?

In any case, here’s my code working on site:

function closeMenu() {
	$w('#menuHeader').hide("FloatOut");
	setTimeout(function () {
		$w('#menuHeaderCloseGroup').hide();
		$w('#menuHeaderGroup').show();
	}, 300);
}
export function menuHeaderCloseButton_click(event) {
	closeMenu();
}

And here’s the code not working using the backend and calling on a Page:

Backend

export function closeMenu(menuHeader, menuHeaderGroup, menuHeaderCloseGroup){
	$w(menuHeader).hide("FloatOut");
	setTimeout(function () {
		$w(menuHeaderCloseGroup).hide();
		$w(menuHeaderGroup).show();
	}, 300);
	console.log("menuClosed");
}

Frontend

import {closeMenu} from 'backend/menuModule';

$w.onReady(function () {
	//TODO: write your page related code here...
	closeMenu($w('#menuHeader').id, $w('#menuHeaderGroup').id, $w('#menuHeaderCloseGroup').id);
});

Thanks for the help!

Hi Felipe,
let me clarify the purpose of backend code in wixcode’s architecture.

you use backend code to run logic that you don’t want to expose to the browser for security reasons, or to do stuff that can’t be done from the browser (like accessing other domains etc.)

note that backend code does not have access to the $w variable since code that runs in the backend cannot interact with the elements on the page.

in your case, you need a different approach.
in order to create and call functions on a page, there’s no need for backend code at all.
simply implement these functions as part of your page code, and call them where necessary.
this is exactly what you did in your working code sample, and I think there’s no good reason to change it.

feel free to elaborate if I’ve missed anything.
thanks!

Thanks a lot Ziv! Then my question will be: is there a way to globally define the functions to be able to call them in all pages? I don’t want to define the function on all pages and having it defined in the Site section as I presented it before hasn’t worked for me yet…

My intention is that the closeMenu() function runs on every page load.

Thanks for your help!

of course, the need is clear.
this is exactly why we have the “public” folder on the site navigation bar (the left bar).
just create that file there, export the function like you did, and call it from wherever it’s needed.

happy coding!

2 Likes

Thank you Ziv! I’ll give it a go

how to add to number in backend “jsw” file

What do you mean? What number? Can you provide your current code? What are you trying to achieve? Please create a new post if it is not related to “Calling a Backend Function .jsw”