Rewriting JavaScript to React doesn't accept jQuery - javascript

I am trying to re-write my old JavaScript code and make it work for React.
The main idea behind this is just including some external data to my 3rd party form.
This is my old JS:
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>
<script>
hbspt.forms.create({
portalId: 'myID',
formId: 'myID',
onFormSubmit: function() {
jQuery('input[name="TICKET.content"]').val(JSON.stringify(window.cart,undefined, 2)).change();
}
});
</script>
And trying to make it work in React:
React.useEffect(() => {
const script = document.createElement('script');
script.src = 'https://js.hsforms.net/forms/v2.js';
document.body.appendChild(script);
script.addEventListener('load', () => {
if (window.hbspt) {
window.hbspt.forms.create({
portalId: 'myID',
formId: 'myID',
onFormSubmit: function() {
jQuery('input[name="TICKET.content"]').val(window.cart).change();
},
target: '#hubspotForm',
});
}
});
});
<div id="hubspotForm"></div>
Trying with react-hubspot-form
onSubmit={function (e) {
e.preventDefault();
const ticket = document.querySelector('input[name="TICKET.content"]');
const nativeInputValueSetter = Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype,'value').set;
nativeInputValueSetter.call(ticket, cart);
const evt = new Event('change', {bubbles: true,});
ticket.dispatchEvent(evt);}}
But with code above I am getting error of jQuery is not being defined. Is there better way how to re-write or am I able to define jQuery somehow?

Why use jQuery?
You can use react setters What is the best way to trigger onchange event in react js
Try
onFormSubmit: function(e) {
e.preventDefault(); // I assume you do not want to submit
const ticket = document.querySelector('input[name="TICKET.content"]');
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeInputValueSetter.call(ticket , window.cart);
const evt = new Event('change', { bubbles: true});
ticket.dispatchEvent(evt);
}

Related

How to get codemirror 'change' event to fire in Grapesjs plugin

I'm building a Grapesjs plugin and have added a 'jscript' trait to a button component, which appears as a codemirror textarea. The idea is for users to be able to edit some javascript code associated with a button. I can't seem to intercept the codemirror area's change event, at least, not the proper codemirror specific version.
Happily, when I edit the codemirror area and change focus, a regular 'change' event triggers the Grapejs onEvent handler within my plugin's editor.TraitManager.addType('jcodemirror-editor', {} - good. I can then store the contents of the codemirror area into the trait.
onEvent({ elInput, component, event }) {
let code_to_run = elInput.querySelector(".CodeMirror").CodeMirror.getValue()
component.getTrait('jscript').set('value', code_to_run);
},
However if we paste or backspace or delete etc. in the codemirror area then the regular 'change' event is never issued!
So I'm trying to intercept the deeper codemirror specific 'change' event which is usually intercepted via cm.on("change", function (cm, changeObj) {} and which is triggered more reliably (unfortunately also on each keystroke). How do I wire this codemirror specific event to trigger the usual onEvent({ elInput, component, event }) {} code?
I have a workaround in place in my https://jsfiddle.net/tcab/1rh7mn5b/ but would like to know the proper way to do this.
My Plugin:
function customScriptPlugin(editor) {
const codemirrorEnabled = true // otherwise trait editor is just a plain textarea
const script = function (props) {
this.onclick = function () {
eval(props.jscript)
}
};
editor.DomComponents.addType("customScript", {
isComponent: el => el.tagName == 'BUTTON' && el.hasAttribute && el.hasAttribute("data-scriptable"),
model: {
defaults: {
traits: [
{
// type: 'text',
type: 'jcodemirror-editor', // defined below
name: 'jscript',
changeProp: true,
}
],
script,
jscript: `let res = 1 + 3; console.log('result is', res);`,
'script-props': ['jscript'],
},
},
});
editor.TraitManager.addType('jcodemirror-editor', {
createInput({ trait }) {
const el = document.createElement('div');
el.innerHTML = `
<form>
<textarea id="myjscript" name="myjscript" rows="14">
</textarea>
</form>
</div>
`
if (codemirrorEnabled) {
const textareaEl = el.querySelector('textarea');
var myCodeMirror = CodeMirror.fromTextArea(textareaEl, {
mode: "javascript",
lineWrapping: true,
});
// This is the 'more accurate' codemirror 'change' event
// which is triggered key by key. We need it cos if we paste
// or backspace or delete etc. in codemirror then the
// regular 'change' event is never issued! But how do we get
// this event to trigger the proper, usual 'onEvent' below?
// Currently cheating and doing the onEvent work here with
// this special handler.
myCodeMirror.on("change", function (cm, changeObj) { // HACK
const component = editor.getSelected()
const code_to_run = myCodeMirror.getValue()
component.getTrait('jscript').set('value', code_to_run);
console.log('onEvent hack - (myCodeMirror change event) updating jscript trait to be:', code_to_run)
})
}
return el;
},
// UI textarea & codemirror 'change' events trigger this function,
// so that we can update the component 'jscript' trait property.
onEvent({ elInput, component, event }) {
let code_to_run
if (codemirrorEnabled)
code_to_run = elInput.querySelector(".CodeMirror").CodeMirror.getValue()
else
code_to_run = elInput.querySelector('textarea').value
console.log('onEvent - updating jscript trait to be:', code_to_run)
component.getTrait('jscript').set('value', code_to_run);
}, // onEvent
// Updates the trait area UI based on what is in the component.
onUpdate({ elInput, component }) {
console.log('onUpdate - component trait jscript -> UI', component.get('jscript'))
if (codemirrorEnabled) {
const cm = elInput.querySelector(".CodeMirror").CodeMirror
cm.setValue(component.get('jscript'))
// codemirror content doesn't appear till you click on it - fix with this trick
setTimeout(function () {
cm.refresh();
}, 1);
}
else {
const textareaEl = elInput.querySelector('textarea');
textareaEl.value = component.get('jscript')
// actually is this even needed as things still update automatically without it?
// textareaEl.dispatchEvent(new CustomEvent('change'));
}
}, // onUpdate
}) // addType
editor.BlockManager.add(
'btnRegular',
{
category: 'Basic',
label: 'Regular Button',
attributes: { class: "fa fa-square-o" },
content: '<button type="button">Click Me</button>',
});
editor.BlockManager.add(
'btnScriptable',
{
category: 'Scriptable',
label: 'Scriptable Button',
attributes: { class: "fa fa-rocket" },
content: '<button type="button" data-scriptable="true">Run Script</button>',
});
}
const editor = grapesjs.init({
container: '#gjs',
fromElement: 1,
height: '100%',
storageManager: { type: 0 },
plugins: ['gjs-blocks-basic', 'customScriptPlugin']
});
According to official Grapesjs documentation on traits integrating external ui components you can trigger the onEvent event manually by calling this.onChange(ev).
So within createInput I continued to intercept the more reliable myCodeMirror.on("change", ... event and within that handler triggered the onEvent manually viz:
editor.TraitManager.addType('jcodemirror-editor', {
createInput({ trait }) {
const self = this // SOLUTION part 1
const el = document.createElement('div');
el.innerHTML = `
<form>
<textarea id="myjscript" name="myjscript" rows="14">
</textarea>
</form>
</div>
`
if (codemirrorEnabled) {
const textareaEl = el.querySelector('textarea');
var myCodeMirror = CodeMirror.fromTextArea(textareaEl, {
mode: "javascript",
lineWrapping: true,
});
myCodeMirror.on("change", function (cm, changeObj) {
self.onChange(changeObj) // SOLUTION part 2
})
}
return el;
},

ChargeBee Drop-in checkout + React: Error

I'm trying to add the drop-in checkout to a react SPA, following https://www.chargebee.com/checkout-portal-docs/drop-in-tutorial.html#implementation. I'm dynamically adding chargebee.js after the rest of the view gets rendered, and then call registerAgain().
componentDidMount() {
const el = document.createElement('script');
el.onload = () => {
window.Chargebee.registerAgain();
// this.setState({ chargebeeReady: true });
};
el.setAttribute('data-cb-site', 'derp-test');
el.setAttribute('src', 'https://js.chargebee.com/v2/chargebee.js');
document.body.appendChild(el);
}
render() {
// [...]
<a
href="javascript:void(0)"
data-cb-type="checkout"
data-cb-plan-id="asdf-test"
>
Subscribe
</a>
// [...]
}
when clicking subscribe I get an error:
Uncaught TypeError: Cannot read property 'getCart' of null
at t.a (event-binding.ts:24)
at Function.value (chargebee.ts:46)
at HTMLScriptElement.el.onload (Subscribe.js:23)
Chargebee instance will be created when DOMContentLoaded event is triggered.Since, you are loading it asynchronously, instance is not getting created. So you can create the instance using Chargebee.init().
componentDidMount() {
const el = document.createElement('script');
el.onload = () => {
window.Chargebee.init({
"site": "derp-test"
});
window.Chargebee.registerAgain();
// this.setState({ chargebeeReady: true });
};
el.setAttribute('src', 'https://js.chargebee.com/v2/chargebee.js');
document.body.appendChild(el);
}

How to add external JS scripts to VueJS Components?

I've to use two external scripts for the payment gateways.
Right now both are put in the index.html file.
However, I don't want to load these files at the beginning itself.
The payment gateway is needed only in when user open a specific component (using router-view).
Is there anyway to achieve this?
Thanks.
A simple and effective way to solve this, it's by adding your external script into the vue mounted() of your component. I will illustrate you with the Google Recaptcha script:
<template>
.... your HTML
</template>
<script>
export default {
data: () => ({
......data of your component
}),
mounted() {
let recaptchaScript = document.createElement('script')
recaptchaScript.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
document.head.appendChild(recaptchaScript)
},
methods: {
......methods of your component
}
}
</script>
Source: https://medium.com/#lassiuosukainen/how-to-include-a-script-tag-on-a-vue-component-fe10940af9e8
I have downloaded some HTML template that comes with custom js files and jquery. I had to attach those js to my app. and continue with Vue.
Found this plugin, it's a clean way to add external scripts both via CDN and from static files
https://www.npmjs.com/package/vue-plugin-load-script
// local files
// you have to put your scripts into the public folder.
// that way webpack simply copy these files as it is.
Vue.loadScript("/js/jquery-2.2.4.min.js")
// cdn
Vue.loadScript("https://maps.googleapis.com/maps/api/js")
using webpack and vue loader you can do something like this
it waits for the external script to load before creating the component, so globar vars etc are available in the component
components: {
 SomeComponent: () => {
  return new Promise((resolve, reject) => {
  let script = document.createElement('script')
  script.onload = () => {
  resolve(import(someComponent))
  }
  script.async = true
  script.src = 'https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places'
  document.head.appendChild(script)
  })
}
},
UPDATE: This no longer works in Vue 3. You will receive this error:
VueCompilerError: Tags with side effect ( and ) are ignored in client component templates.
If you are trying to embed external js scripts to the vue.js component template, follow below:
I wanted to add a external JavaScript embed code to my component like this:
<template>
<div>
This is my component
<script src="https://badge.dimensions.ai/badge.js"></script>
</div>
<template>
And Vue showed me this error:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed.
The way I solved it was by adding type="application/javascript" (See this question to learn more about MIME type for js):
<script type="application/javascript" defer src="..."></script>
You may notice the defer attribute. If you want to learn more watch this video by Kyle
This can be simply done like this.
created() {
var scripts = [
"https://cloudfront.net/js/jquery-3.4.1.min.js",
"js/local.js"
];
scripts.forEach(script => {
let tag = document.createElement("script");
tag.setAttribute("src", script);
document.head.appendChild(tag);
});
}
You can use the vue-head package to add scripts, and other tags to the head of your vue component.
Its as simple as:
var myComponent = Vue.extend({
data: function () {
return {
...
}
},
head: {
title: {
inner: 'It will be a pleasure'
},
// Meta tags
meta: [
{ name: 'application-name', content: 'Name of my application' },
{ name: 'description', content: 'A description of the page', id: 'desc' }, // id to replace intead of create element
// ...
// Twitter
{ name: 'twitter:title', content: 'Content Title' },
// with shorthand
{ n: 'twitter:description', c: 'Content description less than 200 characters'},
// ...
// Google+ / Schema.org
{ itemprop: 'name', content: 'Content Title' },
{ itemprop: 'description', content: 'Content Title' },
// ...
// Facebook / Open Graph
{ property: 'fb:app_id', content: '123456789' },
{ property: 'og:title', content: 'Content Title' },
// with shorthand
{ p: 'og:image', c: 'https://example.com/image.jpg' },
// ...
],
// link tags
link: [
{ rel: 'canonical', href: 'http://example.com/#!/contact/', id: 'canonical' },
{ rel: 'author', href: 'author', undo: false }, // undo property - not to remove the element
{ rel: 'icon', href: require('./path/to/icon-16.png'), sizes: '16x16', type: 'image/png' },
// with shorthand
{ r: 'icon', h: 'path/to/icon-32.png', sz: '32x32', t: 'image/png' },
// ...
],
script: [
{ type: 'text/javascript', src: 'cdn/to/script.js', async: true, body: true}, // Insert in body
// with shorthand
{ t: 'application/ld+json', i: '{ "#context": "http://schema.org" }' },
// ...
],
style: [
{ type: 'text/css', inner: 'body { background-color: #000; color: #fff}', undo: false },
// ...
]
}
})
Check out this link for more examples.
With Vue 3, I use mejiamanuel57 answer with an additional check to ensure the script tag hasn't been loaded already.
mounted() {
const scripts = [
"js/script1.js",
"js/script2.js"
];
scripts.forEach(script => {
let tag = document.head.querySelector(`[src="${ script }"`);
if (!tag) {
tag = document.createElement("script");
tag.setAttribute("src", script);
tag.setAttribute("type", 'text/javascript');
document.head.appendChild(tag);
}
});
// ...
You can load the script you need with a promise based solution:
export default {
data () {
return { is_script_loading: false }
},
created () {
// If another component is already loading the script
this.$root.$on('loading_script', e => { this.is_script_loading = true })
},
methods: {
load_script () {
let self = this
return new Promise((resolve, reject) => {
// if script is already loading via another component
if ( self.is_script_loading ){
// Resolve when the other component has loaded the script
this.$root.$on('script_loaded', resolve)
return
}
let script = document.createElement('script')
script.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
script.async = true
this.$root.$emit('loading_script')
script.onload = () => {
/* emit to global event bus to inform other components
* we are already loading the script */
this.$root.$emit('script_loaded')
resolve()
}
document.head.appendChild(script)
})
},
async use_script () {
try {
await this.load_script()
// .. do what you want after script has loaded
} catch (err) { console.log(err) }
}
}
}
Please note that this.$root is a little hacky and you should use a vuex or eventHub solution for the global events instead.
You would make the above into a component and use it wherever needed, it will only load the script when used.
NOTE: This is a Vue 2.x based solution. Vue 3 has stopped supporting $on.
Are you using one of the Webpack starter templates for vue (https://github.com/vuejs-templates/webpack)? It already comes set up with vue-loader (https://github.com/vuejs/vue-loader). If you're not using a starter template, you have to set up webpack and vue-loader.
You can then import your scripts to the relevant (single file) components. Before that, you have toexport from your scripts what you want to import to your components.
ES6 import:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
- http://exploringjs.com/es6/ch_modules.html
~Edit~
You can import from these wrappers:
- https://github.com/matfish2/vue-stripe
- https://github.com/khoanguyen96/vue-paypal-checkout
The top answer of create tag in mounted is good, but it has some problems: If you change your link multiple times, it will repeat create tag over and over.
So I created a script to resolve this, and you can delete the tag if you want.
It's very simple, but can save your time to create it by yourself.
// PROJECT/src/assets/external.js
function head_script(src) {
if(document.querySelector("script[src='" + src + "']")){ return; }
let script = document.createElement('script');
script.setAttribute('src', src);
script.setAttribute('type', 'text/javascript');
document.head.appendChild(script)
}
function body_script(src) {
if(document.querySelector("script[src='" + src + "']")){ return; }
let script = document.createElement('script');
script.setAttribute('src', src);
script.setAttribute('type', 'text/javascript');
document.body.appendChild(script)
}
function del_script(src) {
let el = document.querySelector("script[src='" + src + "']");
if(el){ el.remove(); }
}
function head_link(href) {
if(document.querySelector("link[href='" + href + "']")){ return; }
let link = document.createElement('link');
link.setAttribute('href', href);
link.setAttribute('rel', "stylesheet");
link.setAttribute('type', "text/css");
document.head.appendChild(link)
}
function body_link(href) {
if(document.querySelector("link[href='" + href + "']")){ return; }
let link = document.createElement('link');
link.setAttribute('href', href);
link.setAttribute('rel', "stylesheet");
link.setAttribute('type', "text/css");
document.body.appendChild(link)
}
function del_link(href) {
let el = document.querySelector("link[href='" + href + "']");
if(el){ el.remove(); }
}
export {
head_script,
body_script,
del_script,
head_link,
body_link,
del_link,
}
And you can use it like this:
// PROJECT/src/views/xxxxxxxxx.vue
......
<script>
import * as external from '#/assets/external.js'
export default {
name: "xxxxxxxxx",
mounted(){
external.head_script('/assets/script1.js');
external.body_script('/assets/script2.js');
external.head_link('/assets/style1.css');
external.body_link('/assets/style2.css');
},
destroyed(){
external.del_script('/assets/script1.js');
external.del_script('/assets/script2.js');
external.del_link('/assets/style1.css');
external.del_link('/assets/style2.css');
},
}
</script>
......
Simplest solution is to add the script in the index.html file of your vue-project
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>vue-webpack</title>
</head>
<body>
<div id="app"></div>
<!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(" ");
for(h=0;h<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
MIXPANEL_CUSTOM_LIB_URL:"file:"===c.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
mixpanel.init("xyz");
</script><!-- end Mixpanel -->
<script src="/dist/build.js"></script>
</body>
</html>
The answer from mejiamanuel57 is great, but I want to add a couple of tips that work in my case (I spent some hours on them). First, I needed to use the "window" scope. Also, if you need to access any Vue element inside the "onload" function, you need a new variable for the "this" instance.
<script>
import { mapActions } from "vuex";
export default {
name: "Payment",
methods: {
...mapActions(["aVueAction"])
},
created() {
let paywayScript = document.createElement("script");
let self = this;
paywayScript.onload = () => {
// call to Vuex action.
self.aVueAction();
// call to script function
window.payway.aScriptFunction();
};
// paywayScript.async = true;
paywayScript.setAttribute(
"src",
"https://api.payway.com.au/rest/v1/payway.js"
);
document.body.appendChild(paywayScript);
}
};
</script>
I worked with this on Vue 2.6. Here there is an explanation about how the trick "let self = this;" works in Javascript:
What does 'var that = this;' mean in JavaScript?
A fast and easy way that i found to do it is like this:
<template>
<div>Some HTML</div>
<component
src="https://unpkg.com/flowbite#1.5.3/dist/flowbite.js"
:is="'script'"
></component>
</template>
mounted() {
if (document.getElementById('myScript')) { return }
let src = 'your script source'
let script = document.createElement('script')
script.setAttribute('src', src)
script.setAttribute('type', 'text/javascript')
script.setAttribute('id', 'myScript')
document.head.appendChild(script)
}
beforeDestroy() {
let el = document.getElementById('myScript')
if (el) { el.remove() }
}
To keep clean components you can use mixins.
On your component import external mixin file.
Profile.vue
import externalJs from '#client/mixins/externalJs';
export default{
mounted(){
this.externalJsFiles();
}
}
externalJs.js
import('#JSassets/js/file-upload.js').then(mod => {
// your JS elements
})
babelrc (I include this, if any get stuck on import)
{
"presets":["#babel/preset-env"],
"plugins":[
[
"module-resolver", {
"root": ["./"],
alias : {
"#client": "./client",
"#JSassets": "./server/public",
}
}
]
}
If you're using Vue 3 and the Composition API (I highly recommend), and you're using <script> tags a lot, you can write a "composable" function for this:
import { onMounted } from "vue";
export const useScript = (src, async = false, defer = false) => {
onMounted(() => {
// check if script already exists
if (document.querySelector(`head script[src="${src}"`)) return;
// add tag to head
const tag = document.createElement("script");
tag.setAttribute("src", src);
if (async) tag.setAttribute("async", "");
if (defer) tag.setAttribute("defer", "");
tag.setAttribute("type", "text/javascript");
document.head.append(tag);
});
};
OR, if you are using VueUse (I also highly recommend), you can use their existing useScriptTag function.
You can use vue-loader and code your components in their own files (Single file components). This will allow you to include scripts and css on a component basis.
well, this is my practice in qiokian (a live2d anime figure vuejs component):
(below is from the file src/qiokian.vue)
<script>
export default {
data() {
return {
live2d_path:
'https://cdn.jsdelivr.net/gh/knowscount/live2d-widget#latest/',
cdnPath: 'https://cdn.jsdelivr.net/gh/fghrsh/live2d_api/',
}
},
<!-- ... -->
loadAssets() {
// load waifu.css live2d.min.js waifu-tips.js
if (screen.width >= 768) {
Promise.all([
this.loadExternalResource(
this.live2d_path + 'waifu.css',
'css'
),
<!-- ... -->
loadExternalResource(url, type) {
// note: live2d_path parameter should be an absolute path
// const live2d_path =
// "https://cdn.jsdelivr.net/gh/knowscount/live2d-widget#latest/";
//const live2d_path = "/live2d-widget/";
return new Promise((resolve, reject) => {
let tag
if (type === 'css') {
tag = document.createElement('link')
tag.rel = 'stylesheet'
tag.href = url
} else if (type === 'js') {
tag = document.createElement('script')
tag.src = url
}
if (tag) {
tag.onload = () => resolve(url)
tag.onerror = () => reject(url)
document.head.appendChild(tag)
}
})
},
},
}
There is a vue component for this usecase
https://github.com/TheDynomike/vue-script-component#usage
<template>
<div>
<VueScriptComponent script='<script type="text/javascript"> alert("Peekaboo!"); </script>'/>
<div>
</template>
<script>
import VueScriptComponent from 'vue-script-component'
export default {
...
components: {
...
VueScriptComponent
}
...
}
</script>
If you are attempting to utilize a variable that is defined within a JavaScript file that is being loaded asynchronously and you receive an 'undefined' error, it is likely because the script has not yet finished loading. To resolve this issue, you can utilize the onload function to ensure that the script has completed loading before attempting to access the variable. As an example:
const script = document.createElement(...) // set attribute and so on...
script.onload = () => {
// do something with some variables/functions/logic from the loaded script
}
You can use the head property in vue to return a custom script
export default {
head: {
script: [{
src: 'https://cdn.polygraph.net/pg.js',
type: 'text/javascript'
}]
}
}

JS / Backbone - My simple script will not fire "validate" in the base model

In App.Models.Task the validate method will not fire.
TO TEST: Edit a task, then press cancel on the popup window.
When you press edit, you can change the task title.
When you cancel, it should VALIDATE and not remove the task title.
Here it is here on jsFiddle:
https://jsfiddle.net/michaelwjoyner/x4xc7rpz/1/
(function(){
window.App = {
Models:{},
Views :{},
Collections:{}
};
window.template = function(){
return Handlebars.compile('{{title}} <button class="edit">Edit</button> <button class="delete">Delete</button>');
};
App.Models.Task = Backbone.Model.extend({
validate: function(attrs) {
if (! attrs.title) {
return 'A task requires a title';
}
}
});
App.Views.Tasks = Backbone.View.extend({
tagName: 'ul',
render: function(){
this.collection.each(this.addOne, this);
return this;
},
addOne: function(task){
// creating a new node view
var taskView = new App.Views.Task({ model : task });
// append to the root element
this.$el.append(taskView.render().el);
}
});
App.Views.Task = Backbone.View.extend({
tagName : 'li',
events : {
'click .edit' : 'editTask'
},
initialize : function(){
this.model.on('change', this.render, this);
},
editTask : function(){
var newTask = prompt('Change task to : ',this.model.get('title') );
this.model.set('title',newTask);
},
render : function () {
console.log('rendered');
compiler = template('taskTemplate');
html = compiler( this.model.toJSON());
this.$el.html( html );
return this;
}
});
App.Collections.Task = Backbone.Collection.extend({
model : App.Models.Task
});
var tasksCollection = new App.Collections.Task([
{
title: 'Go to the store',
priority: 4
},
{
title: 'Cut Hair',
priority: 4
},
{
title: 'Go to Kingdom Hall',
priority: 4
},
]);
var tasksView = new App.Views.Tasks( {collection : tasksCollection} );
$(document).ready( function() {
$("#tasks").html(tasksView.render().el);
});
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script src="js/main.js"></script>
<!-- Setup our templates -->
<h1>Tasks</h1>
<div id="tasks">
</div>
</head>
<body>
</body>
</html>
The below alterations to your editTask method address the issue of the 'removed task title' on canceling from the prompt. prompt returns null on cancellation (which was causing your issue) as seen here:
(https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)
Not entirely sure what you mean by 'should VALIDATE', but a comment in the code below recommends the place to validate the new title.
editTask: function() {
var title = this.model.get('title');
var newTask = prompt('Change task to : ', title);
if (newTask) {
// Run your 'validation' code here? If satisfied, set the title
title = newTask;
}
this.model.set('title', title);
},
use this code.it will work :)
this.model.set({ title : newTask}, { validate : true });
From the backbonejs docs:
By default save checks validate before setting any attributes but you may also tell set to validate the new attributes by passing {validate: true} as an option.
After your prompt you set the value on the model without telling it to validate.
this.model.set('title',newTask);
Instead of passing a key,value pair you may also change attributes by providing an object:
this.model.set({'title': newTask});
Additionally you can pass options to the set method e.g. to signal that you want validation:
this.model.set({'title': newTask}, {validate: true});
This will call your validate method and prevent an empty value being set on the model. However it will not do anything with the message you provided. You can do that by providing a listener for validation errors:
this.model.on('invalid', this.onInvalid, this);
...
onInvalid: function () {
alert(this.model.validationError);
},
Please see the adaptation of your code

Re-render a view

What is the best way to re-render a view after an event takes place (eg. submitting a note). In the below code, I want to re-render the view to show the note that was just added.
var NotesView = SectionBaseView.extend({
model: app.models.Note,
events: {
'submit': 'Notes'
},
Notes: function (e) {
e.preventDefault();
var details = new this.model($('form').serializeObject());
details.url = '/email/Notes';
details
.save()
.done(function () {
app.notifySuccess('Note added successfully.');
});
views['#Notes'].render();
}
});
Notes view is initialized in the document.ready function as follows:
views['#Notes'] = new NotesView({ el: '#Notes', template: app.templates.Notes });
I tried using views['#Notes'].render(); but this doesn't seem to be working.
The default implementation of render is a no-op. Override this function with your code that renders the view template from model data, and updates this.el with the new HTML. A good convention is to return this at the end of render to enable chained calls. Docs
var NotesView = SectionBaseView.extend({
model: app.models.Note,
events: {
'submit': 'Notes'
},
render : function(){
//your code
return this;
},
Notes: function (e) {
var that = this;
e.preventDefault();
var details = new this.model($('form').serializeObject());
details.url = '/email/Notes';
details
.save()
.done(function () {
app.notifySuccess('Note added successfully.');
});
that.render();
}
});
on document.ready
views['#Notes'] = new NotesView({ el: '#Notes', template: app.templates.Notes });
views['#Notes'].render();

Categories