Vue.js - Initialise a variable on page load - javascript

I am currently developing a webapp using Vue.js and JavaScript, and am in the process of consolidating the .js files for performance reasons. Before combining the .js files, I had a separate .js file for each static html page. In each .js file is a method named initialise() which is called on the created hook which calls other initialising methods that initialises the relevant variables. But now that I've combined the .js files, I need some sort of way of calling only the initialising methods relevant to the current page.
One way that I've tried to do this is to have my initialise() method like this:
initialise: function() {
if (this.currentPage=="profile") {
this.getNightmode();
this.getProfile();
this.getTaskTypes();
} else if (this.currentPage=="postRegistration") {
this.getSignUpMethod();
this.getAccountType();
this.getTaskTypes();
}
}
And a vue variable called currentPage which I attempt initialise on page load, in the html body tag, like this <body v-on:load="currentPage='profile'">
v-on:load, however, does not seem to work. Is there any way to initialise a vue variable according to the current page?

I've figured it out. Using the created hook I also initialised currentPage with window.location.pathname, which initialises currentPage the current URL pathname. My initialising method now looks like
initialise: function() {
if (this.currentPage=="/profile.html") {
this.getNightmode();
this.getProfile();
this.getTaskTypes();
} else if (this.currentPage=="/post_registration.html") {
this.getSignUpMethod();
this.getAccountType();
this.getTaskTypes();
}
}
And this calls the correct initialising methods according to the page.

Related

Using Ruby Variables in JavaScript

I'm new to Ruby so I had a question in regards to using some variables throughout my codebase. I have a variable declared in my Ruby file as follows:
#pages = 350
Now, I know that in HAML, I can simply do:
-if #pages = 350, and in HAML with inline javascript, I can do something like:
:javascript
console.log("#{#pages}");
However, I am linking an external JavaScript file in my HAML document, and I was wondering if it would be possible to use my Ruby variables in my external JS document? I need some variables in order to build what I am trying to build. Thanks!
Update as per one of the answers:
In my HAML file, I have the following:
:javascript
printPages(3);
In my external JS file, I have:
$(function() {
window.printPages = function(pages) {
console.log(pages);
}
});
I you are loading static javascript files I really would not recommend trying to insert variables into that code.
Instead, think about how you would provide that to your javascript code.
You could send it to that code as an argument.
<script type="text/javascript" src="./my-external-script.js"></script>
:javascript
runMyExternalFunction(#{#pages})
Or you could add the variable as a data attribute on your page, and your javascript could look for that when it loads.
Haml:
%body data-pages=#pages
JS:
console.log(document.body.dataset.pages) // value of #pages
Update about your javascript:
Using jquery's on page ready event $() for declaring the function is a bad idea. That means that it waits for everything on the page to be compeletely loaded, and then declares the function your page needs.
What you should be doing is setting up all the function that will be needed right away, and then calling those functions when the page is loaded.
They way you have it, the page loads, printPages() is executed (which doesn't exist yet), and then after all that printPages is created and put into the global scope.
So remove the $() from your external script and add it to your HAML instead.
In fact, if your aren't doing anything super fancy with transpiling or bundling, then you can simply declare the function in your external JS file, and it will be available globally. This doesn't work with your code because they way you've declared the function, it would only be available to code within that $() callback.
// js file
function printPages(pages) {
console.log(pages);
}
HAML:
$(() => {
printPages({#pages})
})

jQuery scope with multiple functions

I have a tool that allows a user to create a dashboard and add widgets to it. Each widget is its own JS file that is loaded into the page.
To keep things the same across the board, I create a function called load which is triggered when the document is ready.
The problem is, each of the other modules that are included all have the same function called load which is causing problems.
While I can change the function name to something unique, I would like to see if its possible to keep them all the same where they are locked down to the scope of the file they are in?
/*
Module Details: Department Links - A collection of links specific to the users department or selected department
*/
$(function() {
// Define our moduleID
var moduleID = 1;
// Load our module
load(moduleID, '', false);
// Create a event for dropdown change
$('body').on('select2-selecting', '#Department_' + moduleID, function (e) {
// When the user picks a department, reload this module and fetch those department links.
load(moduleID, e.val, true);
});
});
/*
Load the module
#moduleID: required.
#departmentID: if not passed, the SP will use the viewers departmentID.
#reload: passed when changing the dropdown so we only render the new data and not the whole module
*/
function load(moduleID, departmentID, reload){
... Do other stuff here
}
I guess my question is.. With multiple functions called load in the various js files included, how can I trigger the one specific to its own file?
#binariedMe is correct.. There is nothing like file scope in JavaScript.. You can do like if you have any object which is separate in every file so you can write as follows...
`Object.load = function (){
// do stuff
}`
And you can call object.load for every module you are loading...!!
The problem may be because you would be declaring load function in each js file globally. I have created a plunker with the same setup and each load function is working isolated to other.
Please check the plunker here https://plnkr.co/edit/uZJ8FFwJMfEvPsWAFWwE?p=preview
(function(){ //stuffs of each file
// Don't put any global variable unless you want no scope isolation for the same.
})();

What is the standard workaround for dynamic js files

Is there a standard workaround for something like this in ASP.NET:
//myinclude.js
$(document).ready(function() {
for(recs=0; recs < {{server-side-value}}; recs++) {
// process records
}
});
Note this is a js file. I know about WinForms ability to insert dynamic quoted scripts into the page. But how about a page's js file that is dependent on server-side values? I know you can use something like:
//myview.cshtml
var instance = new MyObject(<%= ServerSideValue =%>);
and include it on the page to pass it to the js file, but I'm wondering about the architecture of keeping js separate from html code so that an html/css designer can work with the template free of javascript; keeping everything separate. I primarily use MVC now.
What are some of the patterns to deal with this? Is the only solution dynamically inserting js into the actual page or having partial views included separately into the page.? Or is there a way to sprinkle server-side values in separated js? In short, no dynamic js files?
I'm not trying to fix an exact project at this time, I have just been curious about this on past projects.
Thanks...
There are multiple ways to achieve this. One of the ways would be populating your data into a Javascript objects on the HTML page directly.
//myview.cshtml
<script>
var pageData = {
name : '#variable1',
value1: #value1
};
</script>
And, in the javascript file:
//pageUI.js
if (pageData) {
$('#page_tile').html(pageData.name);
}
I am sure you can optimize a whole lot (for example, having a single communication between the server side data and the client side code). At the end of the day, you want to make sure that your javascript code can be resusable.
for example one can do this:
A. have the main .js code read any context-specific parameters from the current window like this (page.js):
!function(window){
var configData = window.MyAppNameConfigData;
// rest app code here..
}(window);
B. the server side script can inject these context-specific data in the page's html like this:
<script>
window.MyAppNameConfigData = {
param1: //..
param2: //..
// etc..
};
</script>
Note if needed make sure that the page.js is enqueued/loaded after the data have been injected/inserted (using a script dependency chain for example)
If it's not "inline" (on the View/Page itself), you could do a Partial View/Page:
Trivial example: _PartialJs.cshtml
$(document).ready(function() {
var foo = "#DateTime.Now.Year";
});
Then in your view:
<script>
#Html.Partial("_PartialJs")
</script>
Renders:
<script>
$(document).ready(function() {
var foo = "2015";
});
</script>
Hth...

Loading a script with jQuery in .NET MVC3

I am currently loading a model with jQuery's .load. After it has been successfully loaded, I would like to execute some JavaScript which has dependencies on the loaded model.
buildFindOrderDialog: function () {
workflowDialogContent.load('../../csweb/Orders/FindOrderDialog/', function () {
$.getScript('~/Scripts/FindOrderDialogModel.js');
workflowDialog.dialog('open');
});
}
The load method executes the Order Controller's FindOrderDialog method which returns a ViewModel. After this has loaded, I want to run my FindOrderDialogModel javascript to affect the model client-side.
The above code does not properly load the javascript. I am wondering: does my controller have to provide a method for loading the javascript? The client has no concept of the relative path.
Of course, I could inline the script with the FindOrderDialog view, which would cause it to execute after load, but this seems like a bit of a hack.
UPDATE: My syntax was just a bit off. This works:
buildFindOrderDialog: function () {
workflowDialogContent.load('../../csweb/Orders/FindOrderDialog/', function () {
$.getScript('../Scripts/Orders/FindOrderDialogModel.js');
workflowDialog.dialog('open');
});
},
If I understand your question correctly, how about either
$.getScript('Scripts/FindOrderDialogModel.js');
Alternatively specify the full path:
$.getScript('/My/Full/Path/Scripts/FindOrderDialogModel.js');
Or finally, inject the relative path via ASP.NET:
$.getScript('<%= .NET CODE FOR RETRIEVING PATH USING THE ~ SIGN %>');

How to organize javascript file into smaller pieces?

I currently have one large external javascript file that is used on the page. I currently wrap the code in a self-invoking function because I have other sections that are loaded using ajax tabs, so I want to avoid naming clashes with those other external js files.
The code in the file is organized like below. I would like to split some of the code inside the plannerTab namespace into smaller files, yet still have it be part of that namespace.
How could I do this? Or, do you guys recommend a different approach? Thanks!
// Document Ready
$(function ()
{
// initializes table
plannerTab.plannerTable.init();
});
var plannerTab = (function ()
{
// All the code for the page is in here. I would like to extract sections
// from in here and put them into their own external files while still keeping
// the namespacing
}();
Update
How could I separate parts from within the plannerTab variable into smaller external js files, and still maintain that they are part of the plannerTab namespace? A small example below.
// Scope: plannerTab.config - Would like to store configuartion into a separate file
var config = {
selectors: {
tableId: '#plannerTable',
addTaskId: '#AddTask',
editTaskSelector: '#plannerTable .edit',
dateFilterSelector: '#plannerTable_TimeFilter li',
deleteTaskClass: '.delete',
searchFilter: '#plannerTable_filter',
selectedDateFilter: 'selected-dateFilter',
taskCellSelector: '#plannerTable .task-col',
taskClass: '.taskId'
},
urls: {
addTaskFormURL: '/Planner/Planner/LoadAddTaskForm',
editTaskFormURL: '/Planner/Planner/LoadEditTaskForm',
deleteTaskURL: '/Planner/Planner/DeleteTask',
getTasksByDateRangeURL: '/Planner/Planner/GetTasksByDateRange',
viewTaskURL: '/Planner/Planner/ViewTask'
}
};
Look at this example (from google)
<script type="text/javascript">
function importScript(url){
var tag = document.createElement("script");
tag.type="text/javascript";
tag.src = url;
document.body.appendChild(tag);
}
window.onload = function(){
// imports go here
importScript("foo.js"); // example
};
</script>
I'm assuming that plannerTab becomes an object return result of the self executing function. If you need to add properties or methods to that object dynamically, you can take a look at jQuery.extend() http://api.jquery.com/jQuery.extend/
You would need to modify the external JS to use the jQuery extend method to add onto existing properties and methods of plannerTab. As long as you keep plannerTab a global variable, you will continue adding to it as you import more external js files.
If you are using the module pattern to maintain private variables in plannerTab, be sure to test how those values behave once you use jQuery.extend().

Categories

Resources