I have these classes I want to add to my Parse Cloud Code:
function Rule = {
this.accessor = new Accessor();
this.act = new Action();
}
Rule.prototype.sendEmail = function(email, threshold, bill){
if (this.accessor.check(threshold, bill)){
this.act.actionTake(email, threshold, bill);
}
};
function Accessor = {
}
Accessor.prototype.check = function(threshold, bill){
return bill > threshold;
};
function Action = {
}
Action.prototype.actionTake = function(email, threshold, bill){
//send email code
};
but when I do add it to the very top of the javascript file
I get Update failed with Could not load triggers. The error was Uncaught SyntaxErrorL Unexpected token in main.js:1
Is Parse Cloud Code just for defining background jobs and cloud functions? Is it possible to add "class" definitions to Parse Cloud Code?
thank you
var Rule = function() {
this.accessor = new Accessor();
this.act = new Action();
};
or
function Rule() {
this.accessor = new Accessor();
this.act = new Action();
}
basic js syntax, nothing related to parse
Related
This question already has answers here:
How can I use modules in the browser, but also refer to variables and functions from within DevTools?
(4 answers)
Closed yesterday.
Update:
Looks like by importing another JS file and using the ES6 Modules, devtools compiles a bit different (will need to dive into learning more). The variables I thought were global were not in the module. Was able to fix this by assigning them to:
window.variable_name = variable_name
This allowed me to call the variables from devtools.
I have a project I am working on to practice a few JS skills. For the most part I have everything up and running but have come across an issue I can not seem to remedy.
I have an app.js file that is linked in my index.html. When running the live server from VS code everything works as it should, but when I open devtools to check some of the variables (global) & functions I get "Uncaught referenceError: variable_name is not defined" with a VM#:# reference.
Up to today, I have been able to call the variables from console without a problem.
I have 12 global variables, and all but 1 (submit) have this issue.
App.js:
import { autocomplete } from "./autocomplete.js";
// ######## GLOBAL VARIABLES ############
//------- Selectors ----------
const container = document.querySelector('.search-container');
const searchElement = document.getElementById('search');
const searchInput = document.querySelector('input[name="search-bar"]');
const submit = document.getElementById('search-bar');
const loader = document.querySelector('.loader');
const results = document.querySelector('.results');
const resetButton = document.querySelector('.reset');
const errorMessage = document.querySelector('.error');
const heart = document.querySelector('#favorite');
//------- Arrays & Objects ----------
let names = [];
let pokemon = {};
let bgImages = ["./resources/images/forest_background.jpg", "./resources/images/field.jpg", "./resources/images/galar-scenery.png", "./resources/images/night.jpg", "./resources/images/training.jpg", "./resources/images/poke-background.webp"];
//########## Grab & Store Pokemon Names for Autocomplete ##########
async function loadPokeNames() {
try {
const response = await fetch ('https://pokeapi.co/api/v2/pokemon?limit=250');
if (response.ok) {
const jsonResponse = await response.json();
// console.log(jsonResponse)
for (const poke of jsonResponse.results){
names.push(poke.name);
}
}
// throw new Error('Request Failed!')
} catch(error){
console.log(error);
}
}
//############ Search Function ###############
async function searchPokemon(e) {
e.preventDefault();
let pokeSearchValue = e.srcElement[0].value.toLowerCase();
searchElement.hidden = true;
loader.hidden = false;
try {
const pokeResponse = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokeSearchValue}`);
if (pokeResponse.ok) {
const pokeJSON = await pokeResponse.json();
// Assign Values to Pokemon Object
pokemon.name = pokeJSON["name"];
pokemon.img = pokeJSON["sprites"]["other"]["official-artwork"]["front_default"];
pokemon.hp = pokeJSON["stats"][0]["base_stat"];
pokemon.attack = pokeJSON["stats"][1]["base_stat"];
pokemon.speed = pokeJSON["stats"][5]["base_stat"];
pokemon.defense = pokeJSON["stats"][2]["base_stat"];
pokemon.special_attack = pokeJSON["stats"][3]["base_stat"];
pokemon.special_defense = pokeJSON["stats"][4]["base_stat"];
console.log(pokemon);
createPokeCard(pokemon);
} else {
throw new Error("Something Went Wrong.");
}
} catch (error) {
loader.hidden = true;
errorMessage.hidden = false;
resetButton.hidden = false;
console.log(error);
}
}
// ####### Generates the Pokemon Card #########
function createPokeCard(object) {
const pokeName = document.querySelector('#poke-name p');
const pokeHP = document.querySelector('#hp');
const pokeImg = document.querySelector('#poke-image img');
const pokeAttack = document.querySelector('#attack .num');
const pokeSpeed= document.querySelector('#speed .num');
const pokeDefense = document.querySelector('#defense .num');
const pokeSpecialA = document.querySelector('#special-attack .num');
const pokeSpecialD = document.querySelector('#special-defense .num');
const backgroundImage = document.querySelector('#poke-image')
// Assign values to Results Card
backgroundImage.style.backgroundImage = `url('${bgImages[Math.floor(Math.random() * 6)]}')`;
pokeName.textContent = object.name;
pokeHP.textContent = `${object.hp} HP`;
pokeImg.src = object.img;
pokeAttack.innerText = object.attack;
pokeDefense.textContent = object.defense;
pokeSpeed.textContent = object.speed;
pokeSpecialA.textContent = object.special_attack;
pokeSpecialD.textContent = object.special_defense;
setTimeout(() => {
loader.hidden = true;
results.hidden = false;
resetButton.hidden = false;
}, 3000)
}
// ####### Resets Search & Card #########
function resetSearch() {
searchInput.value = '';
resetButton.hidden = true;
results.hidden = true;
searchElement.hidden = false;
errorMessage.hidden = true;
for (const att in pokemon){
delete pokemon[att];
}
}
//######## Favorite Functions ###########
function hoverFav() {
this.src = '../resources/images/heartline-fill.png';
}
function hoverOutFav() {
this.src = '../resources/images/heartline.png';
}
// ########### EVENTS ##############
window.onload = loadPokeNames;
autocomplete(searchInput, names)
heart.addEventListener('mouseenter', hoverFav);
heart.addEventListener('mouseout', hoverOutFav);
resetButton.addEventListener('click', resetSearch);
submit.addEventListener('submit', searchPokemon);
Linked (correct path) script tag:
<script src="./script/app.js" type="module"></script>
Any help or a point in the right direction would be amazing.
Tried calling global variables from devtools. Got an uncaught referenceError message.
Alright, so I have made a bit of digging around and it turns out the reason this happens is indeed because you're setting the type of the script as a module. Scripts that are run as modules are under strict mode by default, thus they don't allow access to global variables.
Also, they are made to run as a separate scripts(modules) and so any variables defined or imported into them are private by default and are not accessible to the global scope.
As for the error, in normal standard JS scripts, the access of a variable not defined properly(without let/const) will not throw an error, under strict mode however, it converts it into an error and throws it.
Take a look here for more info on differences between standard & module scripts. Also here for info on strict mode.
I've never created a Javascript module/library before so this is a bit new to me so apologizes for my lack of knowing what to google.
I'm creating a library that will hold information from a URL that is provided by a user. I want to parse the URL's path (the part that comes after the domain) as well as retain a header value that's provided by the URL's response.
It's basic but here's what I have so far:
function Link(someURL) {
this.url = someURL;
this.urlPath = "";
this.uuid = "";
this.getPath = function (someURL) {
// do regexp parsing and return everything after the domain
};
this.getUUID = function (someURL) {
// fetch the URL and return what is in the response's "uuid" header
}
}
Ideally, I'd the module to automatically get all the information upon construction:
var foo = new Link("http://httpbin.org/response-headers?uuid=36d09ff2-4b27-411a-9155-e82210a100c3")
console.log(foo.urlPath); // should return "uuid"
console.log(foo.uuid); // should return the contents in the "uuid" header in the response
How do I ensure the this.urlPath and this.uuid properties get initialized along with this.url? Ideally, I'd only fetch the URL once (to prevent rate limiting by the target server).
After a lot of trial and error, I ended up doing something more like this:
class Link {
constructor (url_in) {
const re = RegExp("^https://somedomain.com\/(.*)$");
this.url = re[0];
this.linkPath = re[1];
}
async getUUID() {
const res = await fetch("https://fakedomain.com/getUUID?secret=" + this.linkPath);
this.uuid = res.uuid;
}
async getJSON() {
const res = await fetch("https://fakedomain.com/getJSON?uuid=" + this.uuid);
this.json = await res.json();
}
async initialize() {
await this.getUUID();
await this.getJSON();
}
}
const someLinkData = new Link("https://reallydumbdomain.com/2020/10/4/blog");
someLinkData.initialize()
.then(function() {
console.log(this.json); // this now works
});
I think a future iteration of this will require me to send a promise with the initialize function but for now, this works.
I am trying to use the v3 CAF receiver app using DRM to casting videos, from my IOS app. If I use the basic v3 CAF receiver app (default receiver) it is working fine, but when I using DRM url (dash/.mpd and licenseUrl ) it will throw below error
Error
[ 20.844s] [Error] [INFO] {"type":"LOAD_CANCELLED","requestId":0}
See the below code.
const playerManager = context.getPlayerManager();
const playbackConfig = new cast.framework.PlaybackConfig();
/** Debug Logger **/
const castDebugLogger = cast.debug.CastDebugLogger.getInstance();
var manifestUri = 'https://example.domain.video/prod/drm/1/7e942940-d705-4417-b552-796e8fd25460/Media_1_20_d2aaec7102dc42c09dd54e4f00cbea412019062801270383196000/dash/manifest.mpd';
var licenseServer = 'https://wv.example.domain.com/hms/wv/rights/?ExpressPlayToken=BQALuGDeKZcAJDE2YzAwYTRkLTYwZWYtNGJiZC1hZmEzLTdhMmZhYTY2NzM5OQAAAHCZzHVjRyfs3AEgxFuwPvZsrqMndjiBPzLQ5_VUx6rJOEDD5noQmXJoVP-Va1gQzxfp9eHux15_pEr6g0RxXNZIjlsN6b7SIfpHPyS9iuPQqgvEgq5I_tV9k1lhQvKuqgpBN0Z5BtxCLwHc8xrnLbuUK6fiThcLMR4He_x38reAsumjFYg';
// setting manually licenseUrl from here
playbackConfig.licenseUrl = licenseServer;
playbackConfig.manifestRequestHandler = requestInfo => {
requestInfo.withCredentials = true;
};
playbackConfig.licenseRequestHandler = requestInfo => {
requestInfo.withCredentials = true;
requestInfo.headers = {
// 'Content-type':'application/dash+xml', // trying this also
'Content-type':'application/octet-stream'
}
playbackConfig.licenseUrl = requestInfo.media.customData.licenseUrl;
return playbackConfig;
};
// MessageInterceptor
playerManager.setMessageInterceptor(
cast.framework.messages.MessageType.LOAD,
request => {
const error = new cast.framework.messages.ErrorData(cast.framework.messages.ErrorType.LOAD_CANCELLED);
castDebugLogger.info('Error', error);
if (!request.media) {
error.reason = cast.framework.messages.ErrorReason.INVALID_PARAM;
castDebugLogger.info('reason', error.reason);
return error;
}
if (request.media && request.media.entity) {
request.media.contentId = request.media.entity;
}
return new Promise((resolve, reject) => {
if (!request.media) {
castDebugLogger.error('MyAPP.LOG', 'Content not found');
reject();
} else {
// I have passed manually data (license Url and content Id etc.) from here for testing purpose
const item = new cast.framework.messages.QueueItem();
item.media = new cast.framework.messages.MediaInformation();
item.media.contentId = manifestUri;
item.media.streamType = cast.framework.messages.StreamType.BUFFERED;
// Trying all options of contentType
item.media.contentType = "application/octet-stream";
//request.media.contentType = 'application/x-mpegurl';
//item.media.contentType = "video/mp4";
//request.media.contentType = 'video/mp4';
//request.media.contentType = 'application/dash+xml';
item.media.metadata = new cast.framework.messages.MovieMediaMetadata();
item.media.metadata.title = "Example title";
item.media.metadata.subtitle = "Example subtitle ";
item.media.metadata.images = [new cast.framework.messages.Image("https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg")];
request.media = item.media;
playbackConfig.protectionSystem = cast.framework.ContentProtection.WIDEVINE;
resolve(request);
}
});
});
// start
context.start({
playbackConfig: playbackConfig,
touchScreenOptimizedApp: true
});
LA_URL and .mpd url is working fine with another online shaka player.
Did you check in the remote web inspector if the network request is sent to the licenser when the load request is issued for the encoded dash stream? Most probably this will help to find where the problem is.
Possibly you will have to add some inteligence to your licenseRequestHandler to add a token of some sort. Or possibly there's a CORS issue.
Note: Before you post some code to stackoverflow, it might be wize to clean it up a bit: remove dead code, remove confusing commented code, provide proper indentation. You're wasting brain cycles of everybody reading your code and trying to process what you shared with the world!
function FriendlyChat() {
// statements
}
FriendlyChat.protoype.somemethod = function() {
// statements
};
FriendlyChat.protoype.somemethod2 = function() {
//statements
};
window.onload = function() {
window.friendlyChat = new FriendlyChat();
};
So i noticed the above structure for js while working on a google codelab.
And I have two ques.
in normal objects you have to call the function i.e Object.somemethod()
How does this structure call the methods assigned to it.
From my limited understanding, Firendlychat.protoype.the method treats the
function as an object and the methods are passed to the new object created on
window.onload.Via
inheritance, The object created i.e friendlychat has all these methods.
Yet none of the methods are called in any way. How does this work?
Is there any advantage to structuring your code in this way other than
readability
Note :
Main function
function FriendlyChat() {
this.checkSetup();
// Shortcuts to DOM Elements.
this.messageList = document.getElementById('messages');
this.messageForm = document.getElementById('message-form');
// Saves message on form submit.
this.messageForm.addEventListener('submit', this.saveMessage.bind(this));
this.signOutButton.addEventListener('click', this.signOut.bind(this));
this.signInButton.addEventListener('click', this.signIn.bind(this));
// Toggle for the button.
var buttonTogglingHandler = this.toggleButton.bind(this);
this.messageInput.addEventListener('keyup', buttonTogglingHandler);
this.messageInput.addEventListener('change', buttonTogglingHandler);
// Events for image upload.
this.submitImageButton.addEventListener('click', function(e) {
e.preventDefault();
this.mediaCapture.click();
}.bind(this));
this.mediaCapture.addEventListener('change',
this.saveImageMessage.bind(this));
this.initFirebase();
}
//the methods are setup here
// Sets up shortcuts to Firebase features and initiate firebase auth.
FriendlyChat.prototype.initFirebase = function() {
this.auth = firebase.auth();
this.database = firebase.database();
this.storage = firebase.storage();
// Initiates Firebase auth and listen to auth state changes.
this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
// Saves a new message on the Firebase DB.
FriendlyChat.prototype.saveMessage = function(e) {
e.preventDefault();
}
};
FriendlyChat.prototype.setImageUrl = function(imageUri, imgElement) {
imgElement.src = imageUri;
};
// Saves a new message containing an image URI in Firebase.
// This first saves the image in Firebase storage.
FriendlyChat.prototype.saveImageMessage = function(event) {
event.preventDefault();
var file = event.target.files[0];
// Clear the selection in the file picker input.
this.imageForm.reset();
// Check if the file is an image.
if (!file.type.match('image.*')) {
var data = {
message: 'You can only share images',
timeout: 2000
};
this.signInSnackbar.MaterialSnackbar.showSnackbar(data);
return;
}
// Check if the user is signed-in
if (this.checkSignedInWithMessage()) {
// TODO(DEVELOPER): Upload image to Firebase storage and add message.
}
};
// Signs-in Friendly Chat.
FriendlyChat.prototype.signIn = function() {
var provider = new firebase.auth.GoogleAuthProvider();
this.auth.signInWithRedirect(provider);
};
// Signs-out of Friendly Chat.
FriendlyChat.prototype.signOut = function() {
this.auth.signOut();
};
One of the advantages I've seen when using prototype inheritance was that you can control all instances of an object. For ex:
function FriendlyChat() {
this.chatIsActive = true;
}
FriendlyChat.prototype.deactivateChat = function(...rooms) {
for (chatRoom of rooms) {
chatRoom.chatIsActive = false;
}
};
var chat1 = new FriendlyChat();
var chat2 = new FriendlyChat();
var chatController = new FriendlyChat();
chatController.deactivateChat(chat1, chat2)
console.log(chat1.chatIsActive)
In ES6, however, you can do it:
class FriendlyChat {
constructor() {
this.chatIsActive = true;
}
static deactivateChat(...rooms) {
for (let chatRoom of rooms) {
chatRoom.chatIsActive = false;
}
}
}
var chat1 = new FriendlyChat();
var chat2 = new FriendlyChat();
FriendlyChat.deactivateChat(chat1, chat2)
console.log(chat1.chatIsActive)
And the another advantage of using prototype is that you can save memory spaces when you make an object from new keyword. For instance, the code in ES5 above, you can see chat1 and chat2 I've made by using new. Then chat1 and chat2 will be able to access deactivateChat() method which is in a sharing-space. It's because of the concept, called prototype-chaining.
And the next ES6 version is just a syntactic sugar - under the hood it does the same as ES5 version
I post this as a reference to others who have been faced with this dilemma.
First of all, ONe of the core issues for me was migrating from java, I seemed to be familiar territory but things work a bit different in js.I strongly recommend these links:
Objects in Detail
js Prototype
So the key to why this method works is due to the
window.friendlyapp =new friendlychat()
Now normally in most languages you have an object
obj() {
attr : value
method: function() {}
}
And then to use the method you do
var child = new obj();
child.method();
but in this method the var is made an instance of the window object and thats why none of the methods of the app need to be explicitly called.
How can I catch any exception that occurs in the client side code like "Pause On Caught Exceptions" on chrome developer tools?
I found the solution!
I have used the C# and MVC.
Add a new class to customize your js files bundle like this:
public class CustomScriptBundle : ScriptBundle
{
public CustomScriptBundle(string virtualPath) : base(virtualPath)
{
Builder = new CustomScriptBundleBuilder();
}
public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
Builder = new CustomScriptBundleBuilder();
}
}
And, create another class to change the content of the js files as follows::
class CustomScriptBundleBuilder : IBundleBuilder
{
private string Read(BundleFile file)
{
//read file
FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(#file.IncludedVirtualPath));
using (var reader = fileInfo.OpenText())
{
return reader.ReadToEnd();
}
}
public string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
{
var content = new StringBuilder();
foreach (var fileInfo in files)
{
var contents = new StringBuilder(Read(fileInfo));
//a regular expersion to get catch blocks
const string pattern = #"\bcatch\b(\s*)*\((?<errVariable>([^)])*)\)(\s*)*\{(?<blockContent>([^{}])*(\{([^}])*\})*([^}])*)\}";
var regex = new Regex(pattern);
var matches = regex.Matches(contents.ToString());
for (var i = matches.Count - 1; i >= 0; i--) //from end to start! (to avoid loss index)
{
var match = matches[i];
//catch( errVariable )
var errVariable = match.Groups["errVariable"].ToString();
//start index of catch block
var blockContentIndex = match.Groups["blockContent"].Index;
var hasContent = match.Groups["blockContent"].Length > 2;
contents.Insert(blockContentIndex,
string.Format("if(customErrorLogging)customErrorLogging({0}){1}", errVariable, hasContent ? ";" : ""));
}
var parser = new JSParser(contents.ToString());
var bundleValue = parser.Parse(parser.Settings).ToCode();
content.Append(bundleValue);
content.AppendLine(";");
}
return content.ToString();
}
}
Now, include your js files in application Bundles with your class:
BundleTable.Bundles.Add(new CustomScriptBundle("~/scripts/vendor").Include("~/scripts/any.js"));
Finally, in a new js file write customErrorLogging function as described below, and add it to your project's main html form:
"use strict";
var customErrorLogging = function (ex) {
//do something
};
window.onerror = function (message, file, line, col, error) {
customErrorLogging({
message: message,
file: file,
line: line,
col: col,
error: error
}, this);
return true;
};
Now, you can catch all exceptions in your application and manage them :)
You can use try/catch blocks:
try {
myUnsafeFunction(); // this may cause an error which we want to handle
}
catch (e) {
logMyErrors(e); // here the variable e holds information about the error; do any post-processing you wish with it
}
As the name indicates, you try to execute some code in the "try" block. If an error is thrown, you can perform specific tasks (such as, say, logging the error in a specific way) in the "catch" block.
Many more options are available: you can have multiple "catch" blocks depending on the type of error that was thrown, etc.
More information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
see a small example how you can catch an Exception:
try {
alert("proper alert!");
aert("error this is not a function!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
<body>
<p id="demo"></p>
</body>
put you code in try Block and try to catch error in catch Block.