DYNAMICS 365 HOW TO ADD AND USE NAMESPACE IN JAVASCRIPT
In this previous post,
we have learned how to create, structure and organize the Dynamics 365 Web Resources files.
In this post, we will learn how to add and use namespace in Dynamics 365 JavaScript web resource and how to call the functions.
-
In the JavaScript web resource, add your specific namespace as per the below code
var CAKBlog = CAKBlog || {}; //Create CAKBlog namespace
CAKBlog.Form = CAKBlog.Form || {}; //Create CAKBlog.Form namespace
CAKBlog.Form.Account = function () { //Create CAKBlog.Form.Account namespace
//Functions are added here
}();
-
Add your functions' logic inside, noting that these functions are private and cannot be directly called
CAKBlog.Form.Account = function () {
function onLoad(context) {
console.log("Execute onLoad");
}
function onSave(context) {
console.log("Execute onSave");
}
function onChangeTelephone(context) {
console.log("Execute onChangeTelephone");
}
}();
-
In order to be able to call functions, you have to add public functions as below
return {
OnLoad: onLoad, //public function: private function
OnSave: onSave, //public function: private function
OnChangeTelephone: onChangeTelephone //public function: private function
};
-
Least but not last, the complete JavaScript web resource might look like this
var CAKBlog = CAKBlog || {}; //Create CAKBlog namespace
CAKBlog.Form = CAKBlog.Form || {}; //Create CAKBlog.Form namespace
CAKBlog.Form.Account = function () { //Create CAKBlog.Form.Account namespace
function onLoad(context) {
console.log("Execute onLoad");
}
function onSave(context) {
console.log("Execute onSave");
}
function onChangeTelephone(context) {
console.log("Execute onChangeTelephone");
}
return {
OnLoad: onLoad, //public function: private function
OnSave: onSave, //public function: private function
OnChangeTelephone: onChangeTelephone //public function: private function
};
}();
-
Finally, in order to call functions that are added into the JavaScript web resource, use the following syntax
(<Namespace>.<FunctionName>) in the CRM Forms based on the event you want to use:
-
CAKBlog.Form.Account.OnLoad
-
CAKBlog.Form.Account.OnSave
-
CAKBlog.Form.Account.OnChangeTelephone
-
CAKBlog.Form.Account.OnLoad
-
The below screen shows the executed functions in the browser's console
Bonus Tips:
- Using namespaces in web resources will make your JavaScript more structured and easier to read
- Using namespaces will avoid conflicts when the same function name exists in different web resources
- When an error occur, you will know which JavaScript file is erroneous based on the namespace
- If you want to call a function or a variable from another web resource, you have to use the same syntax <OtherNamespace>.<VariableName>
Hope This Helps!
Comments
Post a Comment