how to add js file in Laravel using webpack.mix.js - laravel-8

In the resources/js folder, I've a LJS.js file that contains only a simply function, See below.
function ljs_isNullBlankEmpty(str) {
var result = true;
if (!str && str.trim().length !== 0) {
result = false;
}
return result;
}
in my webpack.mix.js, I've this:
mix.js('resources/js/app.js', 'public/js')
.js('resources/js/LJS.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css', [])
.sass('resources/sass/main.scss', 'public/css', []);
I then ran the 'npm run dev', and it generated the LJS.js file in the public/js folder. But the content of my resources/js/LJS.js is being placed inside of the '(() => { })()'. Below is what it generated:
/******/ (() => { // webpackBootstrap
var __webpack_exports__ = {};
/*!*****************************!*\
!*** ./resources/js/LJS.js ***!
\*****************************/
function ljs_isNullBlankEmpty(str) {
var result = true;
if (!str && str.trim().length !== 0) {
result = false;
}
return result;
}
/******/ })()
;
why does it puts the content inside of the (() => { })()? How can I call the ljs_isNullBlankEmpty function in my webpage?

Related

input file component is not updating, VueJS

I have some code where I update multiple files using a package.
Add / Remove seems to work if I console.log, but if I do a POST request, on server I get all files, even if I delete them.
Example: I add 3 files, I delete 2 of them and I do a POST, on server I get 3 files. (But on console.log it shows me that I have only 1 which is correct).
Also, I find this article , but I am not sure what to do in my case.
This is a short version of my code.
<div id="upload-files-on-update">
<file-upload
:multiple="true"
v-model="certifications"
input-id="certifications"
name="certifications[]"
#input-filter="inputFilter"
ref="upload">
<span class="button">Select files</span>
</file-upload>
</div>
new Vue({
el: '#upload-files-on-update',
data: function () {
return {
certifications: [],
}
},
components: {
FileUpload: VueUploadComponent
},
methods: {
updateFiles(){
let formData = new FormData();
this.certifications.forEach((file, index) => {
if (!file.status && file.blob) {
formData.append("certifications[]",
{
types: this.accept,
certifications_ids: this.certifications_ids,
}
);
this.loadingButton = true;
}
});
axios
.post("<?php echo $link;?>", formData, {
headers: {
"Content-Type": "multipart/form-data"
},
params:{
types: this.accept,
certifications_ids: this.certifications_ids,
}
})
},
inputFilter(newFile, oldFile, prevent) {
if (newFile && !oldFile) {
if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
return prevent()
}
if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
return prevent()
}
}
if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
newFile.blob = ''
let URL = window.URL || window.webkitURL
if (URL && URL.createObjectURL) {
newFile.blob = URL.createObjectURL(newFile.file)
}
newFile.pending = true;
newFile.thumb = ''
if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
newFile.thumb = newFile.blob
}
}
},
// Remove file from table
removeFile(index) {
this.certifications.splice(index, 1);
},
}
});
I found a solution for this problem.
//I catch ajax request and I make sure that is the request that I want it
var self = this;
$.ajaxSetup({
beforeSend: function (xhr,settings) {
if(settings.type != 'POST'){
return ;
}
if(settings.data.get('controller') != 'wcfm-memberships-registration'){
return ;
}
// Here I set file input as an empty array
settings.data.set('certifications[]',[]);
// Here I add my new files from a VueJS array
self.certifications.forEach((file, index) => {
settings.data.append("certifications[]", file.file);
});
}
});
});

How to update values in QWeb template in odoo dynamically?

I'm trying to develop barcode scanning module to make inventory transfers using barcode scanner.
I made QWeb template and render it with this.$el.html method and I can see that view rendered appropriately. The problem is that values I pass to the template is not updating with client actions. How do I make them dynamically changed when I change them in js script? Code goes here:
barcode-scanner.js
odoo.define('stock.barcode_scanner', function(require) {
'use sctrict';
var AbstractAction = require('web.AbstractAction');
var core = require('web.core');
var QWeb = core.qweb;
var _t = core._t;
var BarcodeAction = AbstractAction.extend({
start: function() {
var self = this;
self.$el.html(QWeb.render("BarcodeHandlerView", {widget: self}));
core.bus.on('barcode_scanned', this, this._onBarcodeScanned);
return this._super();
},
destroy: function () {
core.bus.off('barcode_scanned', this, this._onBarcodeScanned);
this._super();
},
_onBarcodeScanned: function(barcode) {
var self = this;
this._rpc({
model: 'stock.barcode.handler',
method: 'product_scan',
args: [barcode, ],
})
.then(function (result) {
if (result.action) {
var action = result.action;
if (action.type === 'source_location_set') {
self.sourceLocation = action.value;
} else if (action.type === 'product_added') {
if (self.productsList === undefined) {
self.productsList = [];
}
self.productsList.push(action.value);
} else if (action.type === 'destination_location_set') {
self.destionationLocation = action.value;
} else if (action.type === 'validation') {
self.sourceLocation = undefined;
self.productsList = undefined;
self.destinationLocation = undefined;
}
}
if (result.warning) {
self.do_warn(result.warning);
}
});
},
});
core.action_registry.add('stock_barcode_scanner', BarcodeAction);
return {
BarcodeAction: BarcodeAction,
};
});
transfers.xml
<?xml version="1.0" encoding="utf-8"?>
<template id="theme.tp_remove_button">
<t t-name="BarcodeHandlerView">
<div>Source Location: <t t-esc="widget.sourceLocation"/></div>
<div>Destination Location: <t t-esc="widget.destinationLocation"/></div>
</t>
</template>
I am sure that everything is set properly at __manifest__.py - I can see the view, but client action doesn't trigger page update - and client actions are running when I trigger them - I can see my warnings I return from python function. What am I doing wrong? Should I use some other approach to achieve that?
You must to create an action to catch the event when your element change.
odoo.define('stock.barcode_scanner', function(require) {
'use sctrict';
var AbstractAction = require('web.AbstractAction');
var core = require('web.core');
var QWeb = core.qweb;
var _t = core._t;
var BarcodeAction = AbstractAction.extend({
// ***** Add this to catch events on your template
events: {
'change #destination-location': '_onBarcodeScanned',
},
start: function() {
var self = this;
self.$el.html(QWeb.render("BarcodeHandlerView", {widget: self}));
core.bus.on('barcode_scanned', this, this._onBarcodeScanned);
return this._super();
},
destroy: function () {
core.bus.off('barcode_scanned', this, this._onBarcodeScanned);
this._super();
},
action_change_destination: function (newLocation = null) {
if(newLocation === null){
return null;
}else{
let self = this;
console.log("My new awesome destination changing....");
self.destinationLocation = newLocation;
$("#detination-location").html(self.destinationLocation);
}
},
_onBarcodeScanned: function(barcode) {
var self = this;
this._rpc({
model: 'stock.barcode.handler',
method: 'product_scan',
args: [barcode, ],
})
.then(function (result) {
if (result.action) {
var action = result.action;
if (action.type === 'source_location_set') {
self.sourceLocation = action.value;
} else if (action.type === 'product_added') {
if (self.productsList === undefined) {
self.productsList = [];
}
self.productsList.push(action.value);
} else if (action.type === 'destination_location_set') {
self.destionationLocation = action.value;
// ****** GO AND CHANGE YOUR DESTINATION *****
self.action_change_destination(self.destionationLocation);
} else if (action.type === 'validation') {
self.sourceLocation = undefined;
self.productsList = undefined;
self.destinationLocation = undefined;
}
}
if (result.warning) {
self.do_warn(result.warning);
}
});
},
});
core.action_registry.add('stock_barcode_scanner', BarcodeAction);
return {
BarcodeAction: BarcodeAction,
};
});
And in your view should be like this:
<?xml version="1.0" encoding="utf-8"?>
<template id="theme.tp_remove_button">
<t t-name="BarcodeHandlerView">
<div>Source Location: <t t-esc="widget.sourceLocation"/></div>
<div>Destination Location: <span id="destination-location" /></div>
</t>
</template>

Karma unit test fails in phantomjs

After fixing alot of erros in the testing, now Karma output is this:
PhantomJS 1.9.8 (Windows 8 0.0.0) Controller: MainCtrl should attach a list of t hings to the scope FAILED
Error: Unexpected request: GET /api/marcas
No more request expected at ....
api/marcas is an endpoint i've created. code for MainCtrl:
'use strict';
angular.module('app')
.controller('MainCtrl', function ($scope, $http, $log, socket, $location, $rootScope) {
window.scope = $scope;
window.rootscope = $rootScope
$scope.awesomeThings = [];
$scope.things = ["1", "2", "3"];
$http.get('/api/things').success(function(awesomeThings) {
$scope.awesomeThings = awesomeThings;
socket.syncUpdates('thing', $scope.awesomeThings);
});
$scope.addThing = function() {
if($scope.newThing === '') {
return;
}
$http.post('/api/things', { name: $scope.newThing });
$scope.newThing = '';
};
$scope.deleteThing = function(thing) {
$http.delete('/api/things/' + thing._id);
};
$scope.$on('$destroy', function () {
socket.unsyncUpdates('thing');
});
$http.get('/api/marcas').success(function(marcas) {
$scope.marcas = marcas;
socket.syncUpdates('marcas', $scope.response);
$scope.marcasArr = [];
$scope.response.forEach(function(value) {
$scope.marcas.push(value.name);
});
$scope.marcaSel = function() {
for (i = 0; i < $scope.response.length; i++) {
if ($scope.selectedMarca == $scope.response[i].name) {
$scope.modelos = $scope.response[i].modelos;
};
};
};
});
until you didn't posted your test-code, I guess that your test doesn't includes the following code:
beforeEach(inject(function () {
httpBackend.expectGET('/api/marcas').respond(function(){
return {/*some status code*/, {/*some data*/}, {/*any headers*/}};
});
}));
if the karma-runner tries to execute your test-code, there are to get-requests to the $http-service, $http.get('/api/marcas') and $http.get('/api/things'). if one of these backend calls is not expected, karma cannot run the testcode successfully.
if you don't want to do special stuff for each but only return a default with success code for both calls, you can write so:
beforeEach(inject(function () {
httpBackend.expectGET(/api/i).respond(function(){
return {/*some status code*/, {/*some data*/}, {/*any headers*/}};
});
}));

Parse multiple pages with phantomjs

I have made a code that parses all URL-s from a page. Next, I would like to get a href from every parsed URL <div class="holder"></div> and output it to a file and sepparate with a comma.
So far I have made this code. It is able to find all the URL-s need to be parsed and collects them to a comma sepparated file called output2.txt.
var resourceWait = 300,
maxRenderWait = 10000,
url = 'URL TO PARSE HREF-s FROM';
var page = require('webpage').create(),
count = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height : 1024 };
function doRender() {
var fs = require('fs');
var path = 'output2.txt';
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
fs.write(path,page.evaluate(function() {
return $('.urlDIV').find('a')
.map(function() {
return this.href;})
.get()
.join(',');
}), 'w');
phantom.exit()
});
}
page.onResourceRequested = function (req) {
count += 1;
clearTimeout(renderTimeout);
};
page.onResourceReceived = function (res) {
if (!res.stage || res.stage === 'end') {
count -= 1;
if (count === 0) {
renderTimeout = setTimeout(doRender, resourceWait);
}
}
};
page.open(url, function (status) {
if (status !== "success") {
phantom.exit();
} else {
forcedRenderTimeout = setTimeout(function () {
console.log(count);
doRender();
}, maxRenderWait);
}
});
Thanks in advance,
Martti

Mithril redraw only 1 module

If I have like 10 m.module on my page, can I call m.startComputation, m.endComputation, m.redraw or m.request for only one of those modules?
It looks like any of these will redraw all of my modules.
I know only module 1 will be affected by some piece of code, I only want mithril to redraw that.
Right now, there's no simple support for multi-tenancy (i.e. running multiple modules independently of each other).
The workaround would involve using subtree directives to prevent redraws on other modules, e.g.
//helpers
var target
function tenant(id, module) {
return {
controller: module.controller,
view: function(ctrl) {
return target == id ? module.view(ctrl) : {subtree: "retain"}
}
}
}
function local(id, callback) {
return function(e) {
target = id
callback.call(this, e)
}
}
//a module
var MyModule = {
controller: function() {
this.doStuff = function() {alert(1)}
},
view: function() {
return m("button[type=button]", {
onclick: local("MyModule", ctrl.doStuff)
}, "redraw only MyModule")
}
}
//init
m.module(element, tenant("MyModule", MyModule))
You could probably also use something like this or this to automate decorating of event handlers w/ local
Need multi-tenancy support for components ? Here is my gist link
var z = (function (){
//helpers
var cache = {};
var target;
var type = {}.toString;
var tenant=function(componentName, component) {
return {
controller: component.controller,
view: function(ctrl) {
var args=[];
if (arguments.length > 1) args = args.concat([].slice.call(arguments, 1))
if((type.call(target) === '[object Array]' && target.indexOf(componentName) > -1) || target === componentName || target === "all")
return component.view.apply(component, args.length ? [ctrl].concat(args) : [ctrl])
else
return {subtree: "retain"}
}
}
}
return {
withTarget:function(components, callback) {
return function(e) {
target = components;
callback.call(this, e)
}
},
component:function(componentName,component){
//target = componentName;
var args=[];
if (arguments.length > 2) args = args.concat([].slice.call(arguments, 2))
return m.component.apply(undefined,[tenant(componentName,component)].concat(args));
},
setTarget:function(targets){
target = targets;
},
bindOnce:function(componentName,viewName,view) {
if(cache[componentName] === undefined) {
cache[componentName] = {};
}
if (cache[componentName][viewName] === undefined) {
cache[componentName][viewName] = true
return view()
}
else return {subtree: "retain"}
},
removeCache:function(componentName){
delete cache[componentName]
}
}
})();