importing a simple class, results in white screen, but no error - oop

I have been experimenting with importing classes in Javascript and i got it to work using this exact fomular with adding type="module" to the script tag like this:
<script type="module" src="main.js"></script>
And then adding: "import" and "export default", as show down below. When i try to implement this in a working p5 sketch the screen goes white and both me and the console have no clue why?
import Tester from "./test.js";
let test;
let tenp;
function setup() {
createCanvas(900, 900);
tenp = new Tenprint();
test = new Tester();
}
function draw(){
tenp.drawit();
lort.printlort();
}
//
class Tenprint {
constructor() {
this.xx = 0;
this.yy = 0;
this.spacing = 20;
}
drawit() {
stroke(55);
if (random(1) < 0.5) {
fill(2, 24, 242)
line(this.xx, this.yy, this.xx + this.spacing, this.yy + this.spacing);
} else {
line(this.xx, this.yy + this.spacing, this.xx + this.spacing, this.yy);
}
this.xx = this.xx + this.spacing;
if (this.xx > width) {
this.xx = 0;
this.yy = this.yy + this.spacing;
}
}
}
diffrent file in same folder called: test.js
export default class Tester{
constructor(){
}
printlort(){
console.log("LOOORT");
}
}

replace the fill with a stroke because line has no body

You can also create a new script above the main.js tag, with the path to the test.js file.
Then just creating a new isntance without the import statement, but just simply the variable.
This works because the test.js script is loaded before the main.js script.

Related

In Ionic and Vue.js. How to fetch or “call” data from one file to another?

I’m new to both Ionic and Vue.js. I’m taking advantage of this summer break to start learning both.
I’m building a mobile app for this purpose and so far, so good. However, I have found and issue that I hope you could help me with. Namely, how to fetch or “call” data from one file to another (Is it called routing?).
In my app, I am trying to start/open a function named myFunction() from one of the pages (quiz.vue) when I call it using v-on:click="myFunction3".
This function is located in a JS file called quizz.js, and it is located in the assets folder. This is its path: (“./assets/js/quizz.js”).
I have tried many things to make it work and finally it is working as it should. However, I think my solution is not optimal as it keeps throwing “Uncaught TypeErrors” in the console of the Developer’s Tool…even though it works.
My solution was to push the function inside methods: this.$router.push(myFunction3())
Also, when running the app, it says that myFunction() , and other functions in the same quizz.js file, “is define but never used”.
If you could advise me with anything, I would be most grateful. I am still a beginner so please explain it to me in as simple a manner as possible.
methods:{
openMenu(){
menuController.open("app-menu")
},
myFunction3(){
this.$router.push(myFunction3())
},
Below, the quizz.js file:
var mlhttp = new XMLHttpRequest();
mlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
const quiz = myObj.results[0]['question'];
const correctAnswer = myObj.results[0]['correct_answer'];
const incorrect = myObj.results[0]['incorrect_answers'];
incorrect.push(correctAnswer);
shuffle(incorrect);
document.getElementById("ans").innerHTML = quiz;
var text = "";
var val = 0;
var i;
for (i = 0; i < incorrect.length; i++) {
if(incorrect[i] == correctAnswer){
text += "<ion-button fill='outline' id='right' onClick='increment();myFunc();'/><b>" + incorrect[i] + "</b></ion-button></br>";
val = val + 1;
}else{
text += "<ion-button fill='outline' class='wrong' onClick='myFunc2();'/><b>" + incorrect[i] + "</b></ion-button></br>";
}
}
document.getElementById("ans5").innerHTML = text;
}
};
var j=0;
function myFunction3() {
document.getElementById("ans6").innerHTML = "";
mlhttp.open("GET", "https://opentdb.com/api.php?amount=1", true);
mlhttp.send();
j++;
document.getElementById('ans11').innerHTML=j;
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function myFunc(){
document.getElementById("ans6").innerHTML = "<h1 style='color:green'><i class='fa fa-check'></i> That is correct!</h1>";
document.getElementById("right").style.color = "white";
document.getElementById("right").style.backgroundColor = "green";
var audio = new Audio('./assets/sound/win.mp3');
audio.play();
}
function myFunc2(){
document.getElementById("ans6").innerHTML = "<h1 style='color:red'><i class='fa fa-thumbs-down' ></i>Wrong Answer! </h1>";
document.getElementById("right").style.color = "white";
document.getElementById("right").style.backgroundColor = "green";
var x = document.getElementsByClassName("wrong");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "rgba(255, 0, 0, 0.8)";
x[i].style.color = "white";
}
//document.getElementById("wrong").style.color = "red";
var audio = new Audio('./assets/sound/wrong.mp3');
audio.play();
}
var i=0;
function increment() {
i++;
document.getElementById('ans10').innerHTML=i;
}

Vuex loop array of objects and create conditional statement for key:value

i'm am attempting to pull in data through VueX and iterate over an array of objects to get the menu_code. I am successfully get the data i need but i need to show/hide a button according to these conditions:
if ALL of the data in menu_code is NULL, don't show the button.
if one or more of the menu_code data is !== NULL, show the button.
unsure if i'm linking the hasCode data correctly to the button.
// MenuPage.vue
<button v-show="hasMenuCode">hide me if no menu code</button>
<script lang="ts">
import {
Vue,
Component,
Watch,
Prop
} from 'vue-property-decorator';
import {
namespace
} from 'vuex-class';
import MenuItem from "../../models/menu/MenuItem";
export default class MenuPage extends Vue {
#namespace('menu').State('items') items!: MenuItem[];
hasCode = true;
hasMenuCode() {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].menu_code !== null) {
this.hasCode = true;
} else {
this.hasCode = false;
}
}
}
}
</script>
// MenuItem.ts
import AbstractModel from "../AbstractModel";
import Image from '../common/Image';
import MenuRelationship from "./common/MenuRelationship";
import Availability from "../common/Availability";
import Pricing from "../common/Pricing";
interface MenuItemMessages {
product_unavailable_message: string;
}
interface ItemOrderSettings {
min_qty: number;
max_qty: number;
}
export default class MenuItem extends AbstractModel {
name: string;
menu_code: string;
description: string;
image: Image;
has_user_restrictions: boolean;
availability: Availability;
pricing: Pricing;
ordering: ItemOrderSettings;
messages: MenuItemMessages;
prompts: MenuRelationship[];
setMenus: MenuRelationship[];
constructor(props: any) {
super(props);
this.name = props.name;
this.menu_code = props.menu_code;
this.description = props.description;
this.image = props.image;
this.has_user_restrictions = props.has_user_restrictions;
this.availability = new Availability(props.availability);
this.pricing = new Pricing(props.pricing);
this.ordering = props.ordering;
this.messages = props.messages;
this.prompts = props.prompts;
this.setMenus = props.setMenus;
}
}
Base on your requirement, you need to return if there is any item has menu_code, otherwise the loop continues and it only take the value of the final item in this.items
hasMenuCode() {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].menu_code !== null) {
this.hasCode = true;
return
} else {
this.hasCode = false;
}
}
}
Shorter implementation
hasMenuCode() {
return this.items.some(item => item.menu_code !== null)
}

How to dynamicly load files with TypoScript

I want to load for every page the riht criticalCSS File.
So I saved them like this:
fileadmin/critical1.css for TSFE:id=1
fileadmin/critical2.css for TSFE:id=2
and so on. As there are a lot of pages I want the TS to be completely dynamic and NOT like this:
[globalVar = TSFE:id=1]
page {
cssInline {
10 = FILE
10.file = fileadmin/critical1.css
}
}
[global]
I want it like this:
page {
cssInline {
10 = FILE
10.file= fileadmin/critical{page:uid}.css
}
}
or this
page {
cssInline {
10 = FILE
10.file= fileadmin/critical$GLOBALS['TSFE']->id.css
}
}
But it is not working like this. Does anyone know how to do this?
You just need to add the insertData = 1.
Check this code :
page {
cssInline {
10 = FILE
10.file= fileadmin/critical{page:uid}.css
10.file.insertData = 1
}
}
Reference :
https://docs.typo3.org/typo3cms/TyposcriptReference/Functions/Stdwrap.html?highlight=insertdata#insertdata
Alternatively you can achieve it using headerData.
Check this code :
page {
headerData {
10 = TEXT
10.value = {page:uid}
10.insertData = 1
10.wrap = <link rel="stylesheet" type="text/css" href="fileadmin/critical|.css" media="all" />
}
}
Reference : https://docs.typo3.org/typo3cms/TyposcriptReference/Setup/Page/Index.html#headerdata
Hope this helps you!

Can’t access to custom canvas attribute in Vue

Has anyone used this component with Vue?
https://www.npmjs.com/package/aframe-draw-component.
I want to use Advanced Usage with “aframe-draw-component”.
it works with raw html but not vue.js. codepen example
// html
<a-scene fog="type: exponential; color:#000">
<a-sky acanvas rotation="-5 -10 0"></a-sky>
</a-scene>
// js
const chars = 'ABCDEFGHIJKLMNOPQRWXYZ'.split('')
const font_size = 8
AFRAME.registerComponent("acanvas", {
dependencies: ["draw"],
init: function(){
console.log(this.el.components)
this.draw = this.el.components.draw // get access to the draw component
this.draw.canvas.width = '512'
this.draw.canvas.height = '512'
this.cnvs = this.draw.canvas
const columns = this.cnvs.width / font_size
this.drops = []
for (let x = 0; x < columns; x++) {
this.drops[x] = 1
}
this.ctx = this.draw.ctx
},
tick: function() {
this.ctx.fillStyle = 'rgba(0,0,0,0.05)'
this.ctx.fillRect(0, 0, this.cnvs.width, this.cnvs.height)
this.ctx.fillStyle = '#0F0'
this.ctx.font = font_size + 'px helvetica'
for(let i = 0; i < this.drops.length; i++) {
const txt = chars[Math.floor(Math.random() * chars.length)]
this.ctx.fillText(txt, i * font_size, this.drops[i] * font_size)
if(this.drops[i] * font_size > this.cnvs.height && Math.random() > 0.975) {
this.drops[i] = 0 // back to the top!
}
this.drops[i] = this.drops[i] + 1
}
this.draw.render()
}
})
No matter where I put in Vue component, I get this error:
App.vue?b405:124 Uncaught (in promise) TypeError: Cannot read property ‘canvas’ of undefined
at NewComponent.init (eval at
It can’t find the custom dependency “draw”.
Can somebody help me ?
Thanks.
The canvas element is at Your disposal in the el.components.draw.canvas reference.
You can either create Your standalone vue script, or attach it to an existing component like this:
AFRAME.registerComponent("vue-draw", {
init: function() {
const vm = new Vue({
el: 'a-plane',
mounted: function() {
setTimeout(function() {
var draw = document.querySelector('a-plane').components.draw; /
var ctx = draw.ctx;
var canvas = draw.canvas;
ctx.fillStyle = 'red';
ctx.fillRect(68, 68, 120, 120);
draw.render();
}, 100)
}
});
}
})
Working fiddle: https://jsfiddle.net/6bado2q2/2/
Basically, I just accessed the canvas, and told it to draw a rectangle.
Please keep in mind, that Your error may persist when You try to access the canvas before the draw component managed to create it.
My no-brainer solution was just a timeout. Since the scene loads, and starts rendering faster, than the canvas is being made, I would suggest making a interval checking if the canvas element is defined somehow, and then fire the vue.js script.Also keep in mind, that You can work on existing canvas elements with the build in canvas texture: https://aframe.io/docs/0.6.0/components/material.html

Cannot dynamically change a caption 'track' in Video.js

I'm coding a basic video marquee and one of the key requirements is that the videos need to be able to advance while keeping the player in full screen.
Using Video.js (4.1.0) I have been able to get everything work correctly except that I cannot get the captions to change when switching to another video.
Either inserting a "track" tag when the player HTML is first created or adding a track to the 'options' object when the player is initialized are the only ways I can get the player to display the "CC" button and show captions. However, I cannot re-initialize the player while in full screen so changing the track that way will not work.
I have tried addTextTrack and addTextTracks and both show that the tracks have been added - using something like console.log(videoObject.textTracks()) - but the player never shows them or the "CC" button.
Here is my code, any help is greatly appreciated:
;(function(window,undefined) {
// VIDEOS OBJECT
var videos = [
{"volume":"70","title":"TEST 1","url":"test1.mp4","type":"mp4"},
{"volume":"80","title":"TEST 2","url":"test2.mp4","type":"mp4"},
{"volume":"90","title":"TEST 3","url":"test3.mp4","type":"mp4"}
];
// CONSTANTS
var VIDEO_BOX_ID = "jbunow_marquee_video_box", NAV_TEXT_ID = "jbunow_marquee_nav_text", NAV_ARROWS_ID = "jbunow_marquee_nav_arrows", VIDEO_OBJ_ID = "jbunow_marquee_video", NAV_PREV_ID = "jbunow_nav_prev", NAV_NEXT_ID = "jbunow_nav_next";
// GLOBAL VARIABLS
var videoObject;
var currentTrack = 0;
var videoObjectCreated = false;
var controlBarHideTimeout;
jQuery(document).ready(function(){
// CREATE NAV ARROWS AND LISTENERS, THEN START MARQUEE
var navArrowsHtml = "<div id='" + NAV_PREV_ID + "' title='Play Previous Video'></div>";
navArrowsHtml += "<div id='" + NAV_NEXT_ID + "' title='Play Next Video'></div>";
jQuery('#' + NAV_ARROWS_ID).html(navArrowsHtml);
jQuery('#' + NAV_PREV_ID).on('click',function() { ChangeVideo(GetPrevVideo()); });
jQuery('#' + NAV_NEXT_ID).on('click',function() { ChangeVideo(GetNextVideo()); });
ChangeVideo(currentTrack);
});
var ChangeVideo = function(newIndex) {
var videoBox = jQuery('#' + VIDEO_BOX_ID);
if (!videoObjectCreated) {
// LOAD PLAYER HTML
videoBox.html(GetPlayerHtml());
// INITIALIZE VIDEO-JS
videojs(VIDEO_OBJ_ID, {}, function(){
videoObject = this;
// LISTENERS
videoObject.on("ended", function() { ChangeVideo(GetNextVideo()); });
videoObject.on("loadeddata", function () { videoObject.play(); });
videoObjectCreated = true;
PlayVideo(newIndex);
});
} else { PlayVideo(newIndex); }
}
var PlayVideo = function(newIndex) {
// TRY ADDING MULTIPLE TRACKS
videoObject.addTextTracks([{ kind: 'captions', label: 'English2', language: 'en', srclang: 'en', src: 'track2.vtt' }]);
// TRY ADDING HTML
//jQuery('#' + VIDEO_OBJ_ID + ' video').eq(0).append("<track kind='captions' src='track2.vtt' srclang='en' label='English' default />");
// TRY ADDING SINGLE TRACK THEN SHOWING USING RETURNED ID
//var newTrack = videoObject.addTextTrack('captions', 'English2', 'en', { kind: 'captions', label: 'English2', language: 'en', srclang: 'en', src: 'track2.vtt' });
//videoObject.showTextTrack(newTrack.id_, newTrack.kind_);
videoObject.volume(parseFloat(videos[newIndex]["volume"]) / 100); // SET START VOLUME
videoObject.src({ type: "video/" + videos[newIndex]["type"], src: videos[newIndex]["url"] }); // SET NEW SRC
videoObject.load();
videoObject.ready(function () {
videoObject.play();
clearTimeout(controlBarHideTimeout);
controlBarHideTimeout = setTimeout(function() { videoObject.controlBar.fadeOut(); }, 2000);
jQuery('#' + NAV_TEXT_ID).fadeOut(150, function() {
currentTrack = newIndex;
var navHtml = "";
navHtml += "<h1>Now Playing</h1><h2>" + videos[newIndex]["title"] + "</h2>";
if (videos.length > 1) { navHtml += "<h1>Up Next</h1><h2>" + videos[GetNextVideo()]["title"] + "</h2>"; }
jQuery('#' + NAV_TEXT_ID).html(navHtml).fadeIn(250);
});
});
}
var GetPlayerHtml = function() {
var playerHtml = "";
playerHtml += "<video id='" + VIDEO_OBJ_ID + "' class='video-js vjs-default-skin' controls='controls' preload='auto' width='560' height='315'>";
playerHtml += "<source src='' type='video/mp4' />";
//playerHtml += "<track kind='captions' src='track.vtt' srclang='en' label='English' default='default' />";
playerHtml += "</video>";
return playerHtml;
}
var GetNextVideo = function() {
if (currentTrack >= videos.length - 1) { return 0; }
else { return (currentTrack + 1); }
}
var GetPrevVideo = function() {
if (currentTrack <= 0) { return videos.length - 1; }
else { return (currentTrack - 1); }
}
})(window);
The current VideoJS implementation (4.4.2) loads every kind of text tracks (subtitles, captions, chapters) on initialization time of the player itself, so it grabs correctly only those, which are defined between the <video> tags.
EDIT: I meant it does load them when calling addTextTrack, but the player UI will never update after initialization time, and will always show the initialization time text tracks.
One possible workaround is if you destroy the complete videojs player and re-create it on video source change after you have refreshed the content between the <video> tags. So this way you don't update the source via the videojs player, but via dynamically adding the required DOM elements and initializing a new player on them. Probably this solution will cause some UI flashes, and is quite non-optimal for the problem. Here is a link about destroying the videojs player
Second option is to add the dynamic text track handling to the existing code, which is not as hard as it sounds if one knows where to look (I did it for only chapters, but could be similar for other text tracks as well). The code below works with the latest official build 4.4.2. Note that I'm using jQuery for removing the text track elements, so if anyone applies these changes as is, jQuery needs to be loaded before videojs.
Edit the video.dev.js file as follows:
1: Add a clearTextTracks function to the Player
vjs.Player.prototype.clearTextTracks = function() {
var tracks = this.textTracks_ = this.textTracks_ || [];
for (var i = 0; i != tracks.length; ++i)
$(tracks[i].el()).remove();
tracks.splice(0, tracks.length);
this.trigger("textTracksChanged");
};
2: Add the new 'textTracksChanged' event trigger to the end of the existing addTextTrack method
vjs.Player.prototype.addTextTrack = function(kind, label, language, options) {
...
this.trigger("textTracksChanged");
}
3: Handle the new event in the TextTrackButton constructor function
vjs.TextTrackButton = vjs.MenuButton.extend({
/** #constructor */
init: function(player, options) {
vjs.MenuButton.call(this, player, options);
if (this.items.length <= 1) {
this.hide();
}
player.on('textTracksChanged', vjs.bind(this, this.refresh));
}
});
4: Implement the refresh method on the TextTrackButton
// removes and recreates the texttrack menu
vjs.TextTrackButton.prototype.refresh = function () {
this.removeChild(this.menu);
this.menu = this.createMenu();
this.addChild(this.menu);
if (this.items && this.items.length <= this.kind_ == "chapters" ? 0 : 1) {
this.hide();
} else
this.show();
};
Sorry, but for now I cannot link to a real working example, I hope the snippets above will be enough as a starting point to anyone intrested in this.
You can use this code when you update the source to a new video. Just call the clearTextTracks method, and add the new text tracks with the addTextTrack method, and the menus now should update themselves.
Doing the exact same thing (or rather NOT doing the exact same thing)... really need to figure out how to dynamically change / add a caption track.
This works to get it playing via the underlying HTML5, but it does not show the videojs CC button:
document.getElementById("HtmlFiveMediaPlayer_html5_api").innerHTML = '<track label="English Captions" srclang="en" kind="captions" src="http://localhost/media/captiontest/demo_Brian/demo_h264_1.vtt" type="text/vtt" default />';