I'm using a Popup style UI component in a Nuxt.js base project. This is used by many pages and routes, so I declared and initiated as global component plugin when the app starts, like below:
// nuxt.config.js
plugins: [
{ src: '~/plugins/popup/index.js', mode: 'client' },
],
// plugins/toast/index.js
import Vue from 'vue';
import PopupComponent from './Popup.vue';
const PopupConstructor = Vue.extend(PopupComponent);
export default () => {
Vue.use({
install: () => {
let _popup = new PopupConstructor();
window.popup = Vue.prototype.popup = {
appear: _popup.appear,
disappear: _popup.disappear
};
_popup.vm = _popup.$mount();
_popup.dom = _popup.vm.$el;
document.body.appendChild(_popup.dom);
}
});
};
// Popup.vue
// some edit applied for the sake of simplicity
<template>
<div
class="popup"
:class="{
'--error': error,
'--visible': visible
}"
ref="popup"
>
<div class="content" ref="content">
<div class="title">{{title}}</div>
<div class="text">{{detail}}</div>
</div>
</div>
</template>
import gsap from 'gsap';
export default {
data: function () {
return {
visible: false,
title: '',
detail: '',
timer: 3000,
timeout: null,
animationTimeout: null,
};
},
created() {
},
mounted() {
this.$_appear = null;
this.$_disappear = null;
},
beforeDestroy() {
this.$_appear.kill();
this.$_appear = null;
this.$_disappear.kill();
this.$_disappear = null;
},
appear({ title, detail }) {
if (this.visible) {
this.clearTimeout();
}
this.visible = true;
this.$_appear.kill();
this.$_disappear.kill();
this.title = title;
this.detail = detail;
this.$_showAni = gsap.to(this.$refs.popup, 0.5, {
css: {
top: '100px',
opacity: 1
},
onComplete: () => {
this.$_appear = null;
}
});
this.timeout = window.setTimeout(() => {
this.disappear();
}, this.timer);
},
disappear() {
this.clearTimeout();
this.$_disappear.kill();
this.$_disappear = gsap.to(this.$refs.popup, 0.5, {
css: {
top: '100px',
opacity: 0
},
onComplete: () => {
this.$_disappear = null;
this.visible = false;
}
});
},
clearTimeout() {
if (this.timeout) {
window.clearTimeout(this.timeout);
this.timeout = null;
}
}
}
As you see, by this code the Popup vue component's methods(appear, disappear) will be accessible through window.popup, and the component itself will be created, mounted, attached on document.
This works just fine, but the problem is it seems this leads to memory leak. As I profile the memory allocation timeline using Chrome devtool, from some point of time memory allocated with window causes retained(dangling?; could be GC-ed but left due to reference using?) memory.
Is the usage of plugin like above okay? If not, to get the same utility while preventing memory leak, which part should be corrected?
EDIT:
I added the simple version implementation code for Popup which uses GSAP library for an animation. It uses the animation for appear and disappear sequentially.
Related
I am creating undo/redo functionality in VueJS. I watch the settings and add a new element to an array of changes when the settings change. I also have a method for undo when the undo button is clicked.
However, when the button is clicked and the last setting is reverted, the settings are changed and the watch is fired again.
How can I prevent a new element being added to the array of changes if the settings changed but it was because the Undo button was clicked?
(function () {
var Admin = {};
Admin.init = function () {
};
var appData = {
settings: {
has_border: true,
leave_reviews: true,
has_questions: true
},
mutations: [],
mutationIndex: null,
undoDisabled: true,
redoDisabled: true
};
var app = new Vue({
el: '#app',
data: appData,
methods: {
undo: function() {
if (this.mutations[this.mutationIndex - 1]) {
let settings = JSON.parse(this.mutations[this.mutationIndex - 1]);
this.settings = settings;
this.mutationIndex = this.mutations.length - 1;
console.log (settings);
}
},
redo: function() {
}
},
computed: {
border_class: {
get: function () {
return this.settings.has_border ? ' rp-pwb' : ''
}
},
undo_class: {
get: function () {
return this.undoDisabled ? ' disabled' : ''
}
},
redo_class: {
get: function () {
return this.redoDisabled ? ' disabled' : ''
}
}
},
watch: {
undoDisabled: function () {
return this.mutations.length;
},
redoDisabled: function () {
return this.mutations.length;
},
settings: {
handler: function () {
let mutation = JSON.stringify(this.settings),
prevMutation = JSON.stringify(this.mutations[this.mutations.length-1]);
if (mutation !== prevMutation) {
this.mutations.push(mutation);
this.mutationIndex = this.mutations.length - 1;
this.undoDisabled = false;
}
},
deep: true
}
}
});
Admin.init();
})();
Since you make the changes with a button click, you can create a method to achieve your goal instead of using watchers.
methods: {
settings() {
// call this method from undo and redo methods if the conditions are met.
// move the watcher code here.
}
}
BTW,
If you don't use setter in computed properties, you don't need getters, so that is enough:
border_class() {
return this.settings.has_border ? ' rp-pwb' : ''
},
These watchers codes look belong to computed:
undoDisabled() {
return this.mutations.length;
},
redoDisabled() {
return this.mutations.length;
},
I am trying to integrate the webSDK from https://www.pollfish.com/docs/webplugin in our Vue app.
Ideally I want to load jquery only in one component.
I wrote the following code but when I click the button it doesnt work.
Here is an example with working code that does NOT use Vue https://github.com/pollfish/webplugin-rewarded-example/blob/master/index.html but does run locally.
I get no errors and I can console.log(Pollfish) inside the the showFullSurvey method.
My code is:
<template>
<div class="container" v-if="isFreePlan">
<h2>Remove ads and save unlimited projects for 5 days</h2>
<button #click="showFullSurvey">Take {{lengthOfInteraction}} Survey Now</button>
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
data() {
return {
surveyAvailable: false,
lengthOfInteraction: ''
}
},
methods: {
showFullSurvey() {
Pollfish.showFullSurvey();
console.log('show survey')
}
},
mounted() {
const pollFishConfig = {
api_key: "api-key",
debug: process.env.NODE_ENV === 'production' ? false : true,
ready: () => {},
uuid: this.userId,
surveyAvailable: onSurveyAvailable,
surveyNotAvailable: onSurveyNotAvailable,
surveyCompletedCallback: onSurveyCompleted,
userNotEligibleCallback: onUserDisqualified
};
console.log('POllfish config');
const onSurveyAvailable = (data) => {
console.log('SUrvey Available');
};
const onSurveyNotAvailable = () => {
console.log('SUrvey Not Available');
};
const onSurveyCompleted = () => {
console.log('SUrvey Completed');
};
const onUserDisqualified = () => {
console.log('USer Disqualified');
};
this.addJQuery;
this.addPollFishSDK;
},
computed: {
...mapGetters("session", ['userId']),
...mapGetters("account", ["isFreePlan"]),
addJQuery() {
const url = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
if(document.querySelector(`script[src='${url}']`)){ return; }
let jquery = document.createElement('script');
jquery.setAttribute('src', url);
document.body.appendChild(jquery);
console.log('jquery script')
},
addPollFishSDK() {
const url = 'https://storage.googleapis.com/pollfish_production/sdk/webplugin/pollfish.min.js';
if(document.querySelector(`script[src='${url}']`)){ return; }
let pollFishSdk = document.createElement('script');
pollFishSdk.setAttribute('src', url);
document.body.appendChild(pollFishSdk);
console.log('pollfish script')
}
}
}
</script>
In order to integrate our web plugin in your Vue.js app, you need to set the pollfishConfig object in the window. Please be careful with the object's name to be exactly the same as the following example.
window.pollfishConfig = {
api_key: "api-key",
debug: process.env.NODE_ENV === 'production' ? false : true,
ready: () => {},
uuid: this.userId,
surveyAvailable: onSurveyAvailable,
surveyNotAvailable: onSurveyNotAvailable,
surveyCompletedCallback: onSurveyCompleted,
userNotEligibleCallback: onUserDisqualified
};
Also, based on your example, you need to be sure that the jQuery library is loaded first and be available for our WebPlugin SDK. So you need to handle the onload event. An example solution based on your code is the following:
const addScript = (url, onLoad) => {
const scriptExists = document.querySelector(`script[src='${url}']`);
if (!scriptExists) {
let script = document.createElement('script');
document.body.appendChild(script);
script.onload = () => {
onLoad && onLoad();
}
script.src = url;
}
}
addScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', () => {
addScript('https://storage.googleapis.com/pollfish_production/sdk/webplugin/pollfish.min.js')
});
So it seems Vue is not waiting for Stripe to load, natural behavior most probably. I tried coding a watcher to wait for it but it didn't block render until loaded, am I missing something?
<template>
<section>
<div class="px-8 pt-6 pb-12">
testing
</div>
</section>
</template>
<script>
export default {
head: {
script: [
{ src: 'https://js.stripe.com/v3/' },
],
},
data() {
return {
stripeReady: false,
stripeInterval: null,
elements: null,
}
},
watch: {
stripeReady: function(data) {
if (data) {
clearInterval(this.stripeInterval)
this.render()
}
}
},
created() {
let localThis = this
this.stripeInterval = setInterval(function() {
try {
Stripe('pk_test_');
localThis.stripeReady = true;
}
catch {}
}, 500)
},
mounted() {
let stripe = Stripe('pk_test_');
this.elements = stripe.elements();
}
}
</script>
I made a codepen of my issue here https://codepen.io/stevemr/pen/VNQbYe
I have a root Vue instance which maintains the props for a component, VideoPlayer. My root instance has a method called setVideo, which is just assigning some dummy values right now.
Here's the object I'm using in the data of the root instance:
video: {
drive: '',
filename: '',
mediaType: '',
},
Here's the setVideo function:
setVideo: function() {
// Get the drive, filename, and mediaType
this.video.drive = 'hdd1';
this.video.filename = 'game-of-thrones_s01e04.mp4';
this.video.mediaType = 'show';
// Hide all modals and trigger the display of the video player
Event.trigger('hideModal');
Event.trigger('displayVideoPlayer');
},
The Event class is just a wrapper for basic Vue events:
window.Event = new class {
constructor() {
this.vue = new Vue();
}
trigger(event, data = null) {
this.vue.$emit(event, data);
}
listen(event, callback) {
this.vue.$on(event, callback);
}
};
Here's the DOM where my VideoPlayer component is initialized:
<video-player
v-bind:drive="video.drive"
v-bind:filename="video.filename"
v-bind:media-type="video.mediaType"
></video-player>
And finally, here's my VideoPlayer component:
<template>
<div>
<div id="movie-container">
<div
class="video-loader top-most"
v-if="showVideoPlayer && !loaded"
></div>
<video
id="video-player"
ref="video"
v-if="showVideoPlayer && src !== ''"
class="top-most"
v-bind:class="{ hidden: !loaded }"
v-on:click="togglePlay"
controls
autoplay
>
<source v-bind:src="src" v-bind:type="videoType"></source>
</video>
</div>
<div id="time-range-container" v-if="showTimeRange">
<input
id="time-range"
ref="timeRange"
type="range"
min="0"
v-bind:max="duration"
step="30"
v-model:value="currentTime"
/>
</div>
</div>
</template>
<script>
export default {
props: [
'drive',
'filename',
'mediaType',
],
data() {
return {
currentTime: 0,
duration: 0,
loaded: false,
showTimeRange: false,
showVideoPlayer: false,
}
},
computed: {
src: function() {
if(this.filename !== '') {
return
'/video/' + this.drive +
'/' + this.mediaType +
's/' + this.filename;
}
return '';
},
videoType: function() {
var ext = this.filename.split('.')[1];
var type = '';
switch(ext) {
case 'mk4':
case 'm4v':
type = 'webm';
break;
case 'avi':
type = 'ogg';
break;
default:
type = ext;
}
return 'video/' + type;
},
},
created() {
Event.listen('displayVideoPlayer', this.display);
},
methods: {
display: function() {
if(this.src === '') {
return;
}
this.showVideoPlayer = true;
this.loaded = false;
var self = this;
setTimeout(function() {
var interval = setInterval(function() {
var video = self.$refs.video;
if(video.readyState > 0) {
self.loaded = true;
self.duration = Math.round(video.duration);
self.currentTime = video.currentTime;
clearInterval(interval);
}
}, 500);
}, 800);
},
togglePlay: function() {
var video = this.$refs.video;
if(video.paused) {
video.play();
}
if(!video.paused) {
video.pause();
}
},
},
}
</script>
When setVideo is called it should set the VideoPlayer component's props to the dummy values and then the video player should be displayed. But instead when the displayVideoPlayer event is fired, the component props are still set to their default values (empty strings). Most importantly, the src computed property is not being updated before the display method is called, so the display function immediately returns without doing anything.
It's like my component's props and data aren't being updated, even though I can see with the dev tools that they are. It's like it's just not happening fast enough or something.
I've tried making src part of the component's data and setting it in the display function with another function, setSrc. But the same thing happened.
I've also tried moving Event.listen('displayVideoPlayer', this.display); into mounted() instead of created(), also did not fix anything.
If you look at the codepen, the first time you click the button to trigger the setVideo function, the video player component should be displayed, instead it takes 2 clicks.
It seems the problem is a race condition between Vue updates the value and You call display method:
display: function() {
console.log(this.src) // ""
setTimeout(() => console.log(this.src)) // "/video/hdd1/shows/game-of-thrones_s01e04.mp4"
if(this.src === '') {
return
}
This mean you call display method before the value is update.
One way to solve you is add some delay before your call display method:
setVideo: function() {
this.video.drive = 'hdd1'
this.video.filename = 'game-of-thrones_s01e04.mp4'
this.video.mediaType = 'show'
setTimeout(() => {
Event.trigger('displayVideoPlayer')
})
But I think this might get more problems in the future. If you want to rely on props then you should use watcher pattern instead:
watch: {
src (src) {
if(src === '') {
return
}
// ... display
}
}
Or pass those values through your event not on props like:
Event.trigger('displayVideoPlayer', this.video)
I have a Paper instance with a tool that just draws a path on mouseMove and deletes the segments at the start of that path if the number of segments is greater than 50. Everything works perfect this far. this is the code:
<template>
<div>
<canvas id="canvas" resize></canvas>
</div>
</template>
<script>
import paper from 'paper';
export default {
name: 'home',
components: {
},
created() {
paper.install(window);
},
mounted() {
const canvas = this.$el.querySelector('#canvas');
paper.setup(canvas);
const path = new Path();
path.strokeColor = '#f5bb56';
path.strokeWidth = 2;
this.tool = new Tool()
this.tool.onMouseMove = event => {
if (path.segments.length > 50) {
path.removeSegment(0)
};
path.add(event.point);
path.smooth({
type: 'continuous'
});
};
view.draw()
},
};
</script>
<style lang="scss">
#canvas {
width: 100%;
height: 100%;
}
</style>
The problem is that now i want to start deleting segments from that path with an interval of 50 miliseconds but stop executing that when a new segment is added. I'm looking for something to set a variable into a timeout(() => {eraseFunction()}), when the event is not fired for about two seconds.
i added a clearTimeout pointing to the variable that contains it at the start of the mouseMove event and setting it at the end, so if there's a timeout running, i remove it when the mouseMove starts:
export default {
name: 'home',
components: {
},
data() {
return {
tool: null,
path: null,
erase: null,
}
},
created() {
paper.install(window);
},
mounted() {
const canvas = this.$el.querySelector('#canvas');
paper.setup(canvas);
this.path = new Path();
this.path.strokeColor = '#f5bb56';
this.path.strokeWidth = 2;
this.tool = new Tool()
this.tool.onMouseMove = event => {
clearTimeout(this.erase);
if (this.path.segments.length > 50) {
this.path.removeSegment(0)
};
this.path.add(event.point);
this.path.smooth({
type: 'continuous'
});
this.erase = setTimeout(() => {
this.eraseFunction()
}, 2000);
};
view.draw()
},
methods: {
eraseFunction() {
setInterval(() => {
this.path.removeSegment(0);
}, 500);
}
}
};
</script>
the problem is that the timeout is not removed and given a certain amount of time, i can´t draw new segments because they´re deleted inmediately.
You need to clear setInterval also. You are only clearing setTimeout. setInterval is still running an deleting your segments.
ClearInterval need the intervalID you want to clear. The intervalID is given by setInterval call.
You should return the result of setTimout call in eraseFunction:
eraseFunction() {
return setInterval(() => {
this.path.removeSegment(0);
}, 500);
}
And you should assign to this.erase the result of eraseFunction call, instead of the setTimeout:
setTimeout(() => {
this.erase = this.eraseFunction()
}, 2000);