Sharing Javascript Code from Web Resource

Mary Sage April 21, 2021

I'm trying to share javascript code between a plugin and the field descriptors for custom fields.

I created a web resource javascript plugin that looks like the following:

AJS.$(document).ready(function() {

function CALLME() {
alert('CALLME Called');
}
console.log("plugin ready function");
CALLME();
});

 

In a field descriptor for a custom field I have the following code:

<script type="text/javascript">
AJS.$(document).ready(function() {
console.log("field ready function");
CALLME();

});</script>

 

The plugin is loaded before the field descriptor via the console messages.  But I'm getting the error in the field descriptor that 'CALLME' is undefined.

Is what I'm trying to do possible?  Share javascript code across field descriptors and a plugin? 

I could put the code in the 'Summary' field configuration for every Field Configuration but I have many and don't want to duplicate code.

Thanks.

 

1 answer

1 accepted

0 votes
Answer accepted
Maciej Adamczak
Atlassian Team
Atlassian Team members are employees working across the company in a wide variety of roles.
April 22, 2021

Hi @Mary Sage You could use the runtime AMD modules and define the code you want to share using "define" function and then require it using "require" function.

Exmaple:

 

// Definition of the shared module
define('my-plugin-name/my-module-name', [/* we can keep dependencies empty */], function() {
function CALLME() {
alert('CALLME Called');
}

return CALLME;
});

// Next, in the place where you want to use it
AJS.$(document).ready(function() {
console.log("field ready function");

var CALLME = require('my-plugin-name/my-module-name');

CALLME();
});

Here is a link to the AMD module docs:

Thanks,
Maciej Adamczak

Atlassian Developer

Suggest an answer

Log in or Sign up to answer