Organize JS code in MVC app - javascript

I have several JS code in several partials Views.
I think it would be good idea to put all these code in separated JS file to separate JS code from HTML code.
But how do you deal with MVC code inside JS?
The example below is JS code which I have in partial View. I would like to put in into JS file but the JS code has MVC code #Url.Action("ResultForm", "File") and it will not be executed in JS file.
Any suggestion?
Javascript Code
<script type="text/javascript">
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: '#Url.Action("ResultForm", "File")',
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
</script>

I am assuming using a Razor partial for only the js code is not an option. In that case you could use this approach:
in your view.cshtml
<script type="text/javascript">
var Namespace.urlForModule = '#Url.Action("ResultForm", "File")';
</script>
<script type="text/javascript" src="customScript.js"></script>
in you customScript.js
$.ajax({
url: Namespace.urlForModule,
})
The idea is to separate out the Asp.Net MVC specific code from the js code.
The way you want to do that is upto you. As some one else suggested, you could attach data-* attributes to some div and read those. I prefer this, as it expresses my intent clearly.

A solution would be to create a meta tag or a data-* attribute with the desired dynamic value and catch it with JavaScript. This way you can separate the code entirely with minor changes.

You can add hidden field with url:
// View:
#Html.Hidden("LoadResultFormUrl", #Url.Action("ResultForm", "File"))
// js-file
function loadResultForm() {
url = $("#LoadResultFormUrl").val();
...
};

why dont you just create a partial view which contains nothing but js code
and do a renderpartial instead of adding a script tag?

Create a file "somescript.js" and put the code inside a unique public function, extract hard-coded external dependencies and replace them for parameters.
var startXyz = function(resultFormUrl) {
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: resultFromUrl,
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
};
Then, in your page you do:
<script>
$(function(){
startXyz('#Url.Action("ResultForm", "File")');
});
</script>
Now you have a modular function that will startup your page/partial and a script file that do not depends directly from server state and can be reused on the same or another page.
This approach is especially useful if a partial view is rendered more than once per page.

Related

implementation of global variables in an HTML document with Javascript tags of different types

The situation : I use a script (a) in an HTML document to be able to use a particular SDK. Then I use a second script (b) basic to be able to create a Kendo UI table.
My problem : I try to pass data from script (a) to script (b) via global variables but it doesn't work, what can I do?
Info that might help you:
my document is a form framed by tags
I use Camunda. The first script allows me to use the SDK to retrieve the ID of the instance associated with the form being processed. (but I don't think this is the crux of the problem)
I assume that both scripts are read at the same time by the browser, and that's why script (b) can't read the variable simply because it is not yet created in script (a).
The code :
<script type="text/javascript" src="http://localhost:8080/camunda/app/tasklist/scripts/kendo.all.min.js"></script>
<script cam-script type="text/form-script">
var taskService = camForm.client.resource('task');
var processInstanceId = null;
var result = null;
taskService.get(camForm.taskId, function(err, task) {
//alert(JSON.stringify(task));
debugger;
processInstanceId = task.processInstanceId;
$.get("http://localhost:8080/engine-rest/process-instance/"+processInstanceId+"/variables", function(result) {
debugger;
window.alert("coucou");
console.log(result.JsonWeightSetpoints.value);
});
debugger;
console.log(result.JsonWeightSetpoints.value);
debugger;
});
</script>
<script type="text/javascript">
console.log(result.JsonWeightSetpoints.value);
//this is where I implement the Kendo UI grid
</script>
<div id="grid"></div>
I cannot read the content of the result variable in script (b) because it is not defined.
How do I do this?
Custom events solution:
<script type="text/javascript" src="http://localhost:8080/camunda/app/tasklist/scripts/kendo.all.min.js"></script>
<script cam-script type="text/javascript">
var taskService = camForm.client.resource('task');
var processInstanceId = null;
var result = null;
taskService.get(camForm.taskId, function(err, task) {
//alert(JSON.stringify(task));
debugger;
processInstanceId = task.processInstanceId;
$.get("http://localhost:8080/engine-rest/process-instance/"+processInstanceId+"/variables", function(result) {
debugger;
window.alert("coucou");
console.log(result.JsonWeightSetpoints.value);
// the value is available here, we now can trigger an event and send it
document.dispatchEvent(new CustomEvent("handler", {
detail: { value: result.JsonWeightSetpoints.value }
}));
});
debugger;
console.log(result.JsonWeightSetpoints.value);
debugger;
});
</script>
<script type="text/javascript">
console.log(result.JsonWeightSetpoints.value);
//this is where I implement the Kendo UI grid
// event listener, this would get executed only when we want
document.addEventListener("handler", function(event) {
// write you logic here
console.log(event.detail.value);
});
</script>
<div id="grid"></div>
useful resources:
MDN: Creating and triggering
events
Introducing asynchronous JavaScript

how to create javascript library for self-written functions

** want to call common js for all validation for 20 jsp f**
function mAbcRefresher(refresh, refreshTime) {
//function code
}
function QWERTY(address){
//function code
}
function ASDF(address, value, refreshCallback){....
........
........
........`
I just copy these functions to a JS file and include the JS file in my html document. i need some standard way to write this type of validation code
Firstly created that common file eg. common.js. Add it to all your jsp pages. The standered way to write the code in js file
//common.js file
var common={
//function name
formvalidation : function(){
//eg.you want to get all required parts
var elements=$("input:visible, select:visible , textarea:visible");
$.each($(elements) function( index, element ){
//you can get do your code.
$(element).attr("attr");
});
}
//check condition and return false or true
}
above coders for write common functions.
now in jsp to call the function
Add this js file to head
then you can call the function in jsp
like:
$( document ).ready(function() {
//will return true or false
if(common.formvalidation()){
//submit or not
}
});
you can call another function inside this formvalidation() function
just you have assign a variable for this function
var common={
//function name
formvalidation : function(){
var date=this;
var result=date.formDate();
}
formDate : function(){
// do your code
}
}
You can look above code for the idea. definitely it will be helpful for you

Why a JavaScript function with some specific name is not working while others are?

A very interesting problem I am facing these days is regarding one of my JavaScript function. My JavaScript function with some specific name is not working but if I change its name to anything else then it is working. Have a look -
// function to retain the jquery ui css for toolbar
function retain_css() {
alert('hi');
$( "#new_sort_options" ).buttonset();
}
// new sort
$(document).on("click", ".new_sort_button", function() {
var order = $(this).val();
var make_id = $('#new_make_id').val();
$.ajax({
beforeSend : start_loader(),
type : 'POST',
url : '/ajax/new-sort.php',
data : 'order='+order+'&make_id='+make_id,
dataType : 'json',
success : function(data) {
$("#new_results_toolbar").html(data.toolbar);
$("#new_results").html(data.models);
retain_css();
end_loader();
}
});
});
But retain_css() is not working at all. Even alert() is not firing. But if i change its name to anything such as my_fun() then the code works. I don't understand why it is happening so? Any idea? Don't worry about end_loader() function as it has nothing to deal with my problem. I also changed the order of code when retain_css() was being used but didn't work.
Try not to create global functions because it may collide with other frameworks or libraries.
//define private namespace
window.user3779493Functions = {};
//define method
user3779493Functions.retain_css = function() { ... }
//call method
user3779493Functions.retain_css();
Some functions are already programmed like 'alert('hi');', that is a function called alert:
function alert() {
/* do something */
}
That function also doesn't work.

Trouble calling JavaScript function on page load

I have a javascript function that i have named refreshProjects(), what it does is filter a dropdownlist depending on what was selected in a previous dropdownlist. But i need to also filter my list direcktly after the page has finishd loading.
I have tried using the code window.onload = refreshProjects(id) with no sucsses, but onload workes when i use window.onload = alert('This page has finished loading!'), so i know that part off the script works. So how do i call a javascript function on load, i thought that it would be simple but evrything i tried have failed.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
window.onload = refreshProjects(id); <-- Problem
$("#ddCustomers").change(function () {
refreshProjects($(this).val());
});
function refreshProjects(id) {
var projects = $("#ddProjects");
$.get('#Url.Action("FilterProjects","TimeEntry")', { customerId: id },
function (result) {
// clear the dropdown
projects.empty();
//Add a deafult "null" value
$("#ddProjects").get(0).options[0] = new Option("[ - No project - ]", "-1");
// rebuild the dropdown
$.each(result, function (i, e) {
projects.append($('<option/>').text(e.Text).val(e.Value));
});
});
}</script>
}
This is for MVC 4.5.
Try changing window.onload = refreshProjects(id); to:
window.onload = function() { refreshProjects($("#ddCustomers").val()); };
Onload expects a callback function. You were directly executing refreshProjects() and setting the return value as the onload.
But since you seem to be using jQUery, you could do the following:
$(function() {
refreshProjects($("#ddCustomers").val());
});
This will execute refreshProjects when the document is ready (which actually is before window load).
You can also try to use the following:
$(document).ready(function () {
refreshProjects(id);
});
This should work aswell if you are using jQuery.

Get text file contents using JQuery in an external file

I have an external javascript file that I want to use to collect the contents of a number of text files. JQuery .get() seems the most obvious choice. I can make this work if the JQuery is in the page, but not when the JQuery is in the external file. I'm missing something hugely simple...and I am currently mixing normal javascript with JQuery in the same file which I fear is poor form.
All files I am trying to access are within the same file structure. Currently I have the following in my external .js:
function addPanels() {
// eventually loop over list of local HTML files
// and do some stuff with the results...
fileContents = readHTMLFile();
}
jQuery(function($){
readHTMLFile = $.get('../html/test.html', function(data) {
alert('Loaded something');
return(data);
});
});
My HTML page contains the following:
<script type="text/javascript">
$(document).ready(function(){
addPanels();
});
</script>
Pretty sure this is a RTFM moment so direction towards the right manual/tutorial would be great!
Dan
The jQuery.get is a asynchronous function, with a callback that executes when the server returns the requested document. Therefore, you cannot return any data from the method.
function addPanels() {
// will not work
fileContents = readHTMLFile();
}
...
readHTMLFile = $.get('../html/test.html', function(data) {
// will not work
return(data);
});
This however, will work:
var addPanelCallback = function(html) {
// append html (or something like that)
alert(html);
};
var addPanel = function(url) {
$.get(url, addPanelCallback);
};
addPanel('../html/test1.html');
addPanel('../html/test2.html');
Example: http://jsfiddle.net/FgyHp/
In your script "readHTMLFile" is not known by function "addPanels", you should put them in same level.
This script should works
<script type="text/javascript">
(function($){
var readHTMLFile = function(url){
var toReturn;
$.ajax({
url: url,
async: false
}).done(function(data){
toReturn = data;
});
return toReturn;
};
$.addPanels = function(url){
fileContents = readHTMLFile(url);
};
})(jQuery);
</script>
And in your page you can call it like that:
<script type="text/javascript">
$(document).ready(function(){
$.addPanels('../test/test.html');
});
</script>

Categories