How do I extend loader widget in Magento 2 so that a background image is shown everytime the loader appears - magento2

I have been trying to extend magento 2's $.mage.loader widget. I have have a requirejs-config.js file with the following lines
var config = {
map: {
'*': {
'mage/loader' : 'Youssuph_Bakerscheckout/js/custom-mage-loader'
}
}
};
And the content of custom-mage-loader.js file is
define([
'jquery',
'mage/template',
'jquery/ui',
'mage/translate'],
function ($, mageTemplate) {
'use strict';
$.widget("bakers.loader", $.mage.loader, {
options: {
icon: '',
texts: {
loaderText: $.mage.__('Please wait...'),
imgAlt: $.mage.__('Loading...')
},
template:
'<div class="loading-mask" data-role="loader">' +
'<div class="loader">' +
'<img alt="<%- data.texts.imgAlt %>" src="'+loadingBakersLogo+'">' +
'<p><%- data.texts.loaderText %></p>' +
'</div>' +
'</div>'
}
});
return $.bakers.loader;
});
i have confirmed that this file loads in the browser but it just doesn't work. The loader works normally during page load and I see error message -
Base is not a function
What am I doing wrong?

Your requirejs-config.js it's right, but your js file no, change the params like this:
define([
'jquery',
'jquery/ui',
'mage/loader'],
function ($) {
$.widget('your_namespace.loader', $.mage.loader, {
options: {
texts: {
loaderText: $.mage.__('Foo')
},
template:
'<div>Your template</div>'
}
});
return $.your_namespace.loader;
});
Now use: jQuery('body').loader('show') and see your new custom loader!

Its been a while but if anybody else stumbles upon this answer.
vjurado is not correct. The mistake lays in requirejs-config.js. Correct will be a reference withouth the "mage/", like this:
var config = {
map: {
'*': {
'loader' : 'Youssuph_Bakerscheckout/js/custom-mage-loader'
}
}
};
The custom-mage-loader.js is correct as posted in the initial question.

Related

How can i read external json file in Azure-devops-extension development?

I am trying to read json file inside "index.html" file of the project, since for azure devops extension we already have require.js library, hence wanted to use the same capability of it to import "config.json" file inside "index.html" file.
basic file structure:
|-index.html
|-static  |-icon.png
|    |-config.json
|-vss-extension.json
my index.html file look somewhat like this :
init block
VSS.init({
explicitNotifyLoaded: true,
usePlatformScripts: true,
setupModuleLoader: true,
moduleLoaderConfig: {
paths: {
"Static": "static"
}
}
});
require block
VSS.require(
["TFS/WorkItemTracking/Services", "Static/config"],
function (_WorkItemServices, ConfigJson) {
VSS.ready(function(){
VSS.register(VSS.getContribution().id, function () {
return {
// Called when the active work item is modified
onFieldChanged: function (args) {
console.log(
"inside onfield : " +
JSON.stringify(ConfigJson)
);
}
....
};
});
VSS.notifyLoadSucceeded();
})
});
My vss-extension.json file :
File block
"files": [
{
"path": "static/config.json",
"addressable": true,
"contentType": "application/json"
},
....
]
I am always getting require.js Script error: https://requirejs.org/docs/errors.html#scripterror
Took reference from:
https://github.com/ALM-Rangers/Show-Area-Path-Dependencies-Extension/blob/master/src/VSTS.DependencyTracker/vss-extension.json for vss-extension file.
https://github.com/ALM-Rangers/Show-Area-Path-Dependencies-Extension/blob/master/src/VSTS.DependencyTracker/index.html for index.html
I am afraid that you couldn't directly get the content of the json file.
But you could try to use the HTTP request to get the content.
Please refer to the following sample:
onFieldChanged: function (args) {
var request = new XMLHttpRequest();
request.open('GET', 'config.json', true);
request.send(null);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var type = request.getResponseHeader('Content-Type');
console.log( "inside onfield : " + JSON.stringify(request.responseText));
}
}
Check out these two tickets for details.
Loading a JSON file in a VSTS extension
read local JSON file into variable
Is VSS using unmodified RequireJS? If yes, then you can use JSON plugin, which will help:
https://github.com/millermedeiros/requirejs-plugins
Using it is pretty simple, you just have to add a prefix json! when specifying a json file as a dependency:
VSS.require(
["TFS/WorkItemTracking/Services", "json!Static/config"],
function (_WorkItemServices, ConfigJson) {
VSS.ready(function(){
VSS.register(VSS.getContribution().id, function () {
return {
// Called when the active work item is modified
onFieldChanged: function (args) {
console.log(
"inside onfield : " +
JSON.stringify(ConfigJson)
);
}
....
};
});
VSS.notifyLoadSucceeded();
})
});

Getting an ' instance.requestPaymentMethod is not a function' in Braintree's sample

I'm getting an instance.requestpaymentmethod is not a function when I was just following along the tutorial for custom-field integration found here:
https://developers.braintreepayments.com/start/tutorial-hosted-fields-node
The error happens when I click on the "Pay" button.
Did anyone solve this problem? My assumption is that the code isn't updated or the script sources changed somewhat. If anyone from Braintree can actually help, that'll be great.
Thanks!
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
I took a look at the example code snippet in the guide you shared and I was able to find the culprit. First off, the error you're getting is expected as the requestPaymentMethod method actually belongs to our Drop-In UI solution and the Hosted Fields JS library doesn't have such module. I informed our Documentation team to get that code example updated.
That being said, you can find a working example in our Hosted Fields guide. If you check the function (hostedFieldsErr, hostedFieldsInstance) callback function, you'll see that the payment nonce is created by the tokenize function of the hostedFieldsInstance.
I also ran into this issue today. Use the following code in <script> tag. It will work for you.
var form = document.querySelector('#hosted-fields-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: '<YOUR_TOKENIZATION_KEY>'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
console.log('Got a nonce: ' + payload.nonce);
$.ajax({
type: 'POST',
url: '<YOUR_API_URL>',
data: { 'paymentMethodNonce': payload.nonce }
}).done(function (result) {
hostedFieldsInstance.teardown(function (teardownErr) {
if (teardownErr) {
console.error('Could not tear down Drop-in UI!');
} else {
console.info('Drop-in UI has been torn down!');
$('#submit-button').remove();
}
});
if (result.success) {
$('#checkout-message').html('<h1>Success</h1><p>Your Drop-in UI is working! Check your sandbox Control Panel for your test transactions.</p><p>Refresh to try another transaction.</p>');
} else {
console.log(result);
$('#checkout-message').html('<h1>Error</h1><p>Check your console.</p>');
}
});
});
}, false);
});
});

Why is CKEditor refusing my custom tag?

With a custom CKEditor plugin I am trying to insert a custom HTML tag, but the tag gets removed as soon as it is inserted into the editor. My plugin.js file:
CKEDITOR.plugins.add( 'tweet', {
icons: 'tweet',
init: function( editor ) {
editor.addCommand( 'insertTweet', {
allowedContent: 'tweet[:id]',
requiredContent: 'tweet',
exec: function( editor ) {
console.log('inserting');
editor.insertHtml( '<tweet :id="\'123\'" />' ); // also tried <tweet />
// editor.insertHtml( '[tweet :id="\'123\'" /]' ); // this works
}
});
editor.ui.addButton( 'tweet', {
label: 'Insert tweet',
command: 'insertTweet',
toolbar: 'insert,0'
});
}
});
The way I am adding the plugin for Bolt CMS backend:
function run() {
var extrasAdded = false;
if (typeof(CKEDITOR) == 'undefined') return;
CKEDITOR.plugins.addExternal('tweet', '/assets/plugins/tweet/plugin.js', '');
CKEDITOR.on('instanceReady', function (event, instance) {
if (extrasAdded === true) return;
var config = event.editor.config;
config.toolbar.push(
{ name: 'insert', items: [ 'tweet' ] }
);
config.extraPlugins += (config.extraPlugins ? ',' : '') + 'tweet';
config.extraAllowedContent = 'tweet'; // also tried 'tweet[:id]'
CKEDITOR.instances['body'].destroy();
CKEDITOR.replace('body', config);
extrasAdded = true;
});
}
if (document.readyState!='loading') run();
else document.addEventListener('DOMContentLoaded', run);
Can someone smart see why my tag is rejected?
So it turns out that we don't need the allowedContent or requiredContent properties in the plugin.js script. What did the trick was to tweak the editor's HTML DTD rules. In my case I got a reference to the editor in the instanceReady callback and tweeked it like this:
// name = 'tweet'
editor.filter.allow(name + "[!*]", name, true);
CKEDITOR.dtd[name] = CKEDITOR.dtd;
CKEDITOR.dtd.$empty[name] = 1; // allow self-closing tag
CKEDITOR.dtd.$blockLimit[name] = 1;
CKEDITOR.dtd.$nonEditable[name] = 1;
CKEDITOR.dtd.$object[name] = 1;
CKEDITOR.dtd.$inline[name] = 1; // $block won't work!
You can also see a full gist of it.

how to use third party javascript code in magento2 payment?

I am facing problem while adding third party javascript code in my payment module in magento2.
following is my code.
define(
[
'Magento_Payment/js/view/payment/cc-form',
'jquery',
'Vendorname_Modulename/js/stsdk'
'Magento_Payment/js/model/credit-card-validation/validator'
],
function (Component, $, STDirect) {
'use strict';
return Component.extend({
defaults: {
template: 'Vendorname_Modulename/payment/module-form'
},
getCode: function() {
return 'vendor_module';
},
isActive: function() {
return true;
},
validate: function() {
STDirect.setupSDK('23842', "testnumber", 'typeofenv');
STDirect.card.createToken(number, exp_month, exp_year, ccv, function (result) {
var secretkey = '';
if(result.status==0){
secretkey = result.card.secretkey;
}
document.write(JSON.stringify(result));
alert(secretkey);
});
var $form = $('#' + this.getCode() + '-form');
return $form.validation() && $form.validation('isValid');
}
});
}
);
I have tried above code, stsdk.js is loaded in network but it gives me following error :
ReferenceError: STDirect is not defined
STDirect.setupSDK('23842', "testnumber", 'sandbox');
I have also checked by load this js file in header but same error appear.
My question is how to execute third party javascript code in define scope.
I tried with the custom javascript function after define function but it is also not callable from validate function and when I use require[] function within define function it raise error.
I appreciate any help.

adding external plugin in CKEditor 3.6

I am trying to add an external plugin in ckeditor but it looks that I am not registering correctly my plugin and it isn' showing.
1.- I tried adding it directly to the CKEditor config file and it didn't work.
CKEDITOR.editorConfig = function(config) {
config.toolbar = [
['Bold'],['Italic'],['myplugin']
]
};
2.- Tried adding it to the html file when initiating CKEditor and also didn't work.
var editor = CKEDITOR.replace( 'editor1',
{
removePlugins : 'forms,table,tabletools',
extraPlugins : 'msugetprop,msuforms,msutable,msutabletools,msumobile',
toolbar :
[
['Cut','Copy','PasteText','Preview'],
['Undo','Redo','-','SelectAll'],
['MsuForm','MsuGetProp','MsuCheckbox', 'MsuRadio', 'MsuTextField', 'MsuTextarea', 'MsuSelect', 'MsuButton', 'MsuTable', 'MsuHiddenField'],
'/',
['Styles','-','NumberedList','BulletedList','-','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Link','Unlink','Anchor'],
['Source','-','About'],
['myplugin'],
]
});
3.- My plugin is under /ckeditor/plugins/myplugin with filename plugin.js
(function() {
var o = { exec: function(p) {
url = baseUrl + "/GetSomeData";
$.post(url, function(response) {
alert(response)
});
}
};
CKEDITOR.plugins.add('myplugin', {
init: function(editor) {
editor.addCommand('myplugin', o);
editor.ui.addButton('myplugin', {
label: 'myplugin',
icon: this.path + 'myplugin.png',
command: 'myplugin'
});
}
});
})();
What am I missing ?
Solved.
forgot to add 'myplugin" under extraPlugins.