How to preserve jQuery.ajax.data object when using closure compiler? - google-closure-compiler

When using closure compiler with ADVANCED_OPTIMIZATIONS, jQuery.ajax.data object is changed:
$.ajax({
type: "POST",
url: "ajax.php",
data: {
act : "some"
},
success : function(data){}
});
jQuery.ajax.data object is converted to {L : "some"}
I can use quotes, like 'act' : "some", but I want this to work without quotes.
In my externs file there is:
/** #type {Object.<string,*>} */
jQuery.ajax.data;
But this doesn't work. Closure compiler version 1043

Try the externs with something like :
var jQuery = {};
jQuery.ajax = {
data: ''
}
This will not rename 'jQuery.ajax' and 'jQuery.ajax.data'

Related

How to pass route param while using Inertia manual visit

How can I pass the route param while using Inertia manual visit, for example:
Route:
Route::post('/explore/gallery/like/{$post}', [ExploreController::class, 'likeToggle'])
->name('explore.post.like');
Component:
Inertia.visit(route('explore.post.like'),
{
method: 'post',
preserveScroll: true,
data: {
$post: this.id
},
},
);
but is shows the error tho,
Error occur in Ziggy, and says you need pass $post,
Ok, Change route('explore.post.like') to route('explore.post.like', this.id)
According Ziggy documentation you can also use like :
route('explore.post.like', this.id)
route('explore.post.like', [this.id])
route('explore.post.like', { $post: this.id })
A simple solution would be:
Inertia.post(route('explore.post.like', [this.id, 'if you have other params']), {}, {
preserveScroll: true,
});
Pls make sure the order is correct, follow the order of your route's param

FileSaver.js is saving corrupt images

This was working fine and suddenly stopped working. I'm not sure what exactly changed.
I need to download multiple images via URLs.
I'm using the following code:
https://plnkr.co/edit/nsxgwmNYUAVBRaXgDYys?p=preview
$http({
method:"GET",
url:"imageurl"
}).then(function(response){
saveAs(new Blob([response.data]), "image.jpg");
},function(err){
});
The files have different sizes, they are not 0 bytes.
For others coming here, check this solution.
What needed to be done was to add responseType: "blob" to the request:
$http({
method:"GET",
url:"imageurl",
responseType: "blob"
})
.then(...)
Here is the documentation for the responseType valid values, where it says the default is "" so the response is treated as text:
"": An empty responseType string is treated the same as "text", the default type (therefore, as a DOMString).
"blob:": The response is a Blob object containing the binary data.
Following code worked for me:
axios.get(`http://localhost:61078/api/values`, {
responseType: 'blob',
}).then(response => {
if (response) {
var FileSaver = require('file-saver');
FileSaver.saveAs(new Blob([response.data]), "image.png");
}
});

How to get a variable from another file in gruntfile

I am new to grunt.
My requirement is that I need to uglify my files based on the variable set on another file.
Let's say I have some abc.js file in which I have a variable var is_uglify = true;
I need to read the value of the variable in gruntfile and perform the build accordingly.
If variable is true, I need to do:
grunt.registerTask('build', ['clean:build','uglify']);
otherwise
grunt.registerTask('build', ['clean:build']);
Can anyone help with this?
This can be achieved by:
Defining a Custom Task - namely getValue in the gist below.
In the getValue Task/Function utilize grunt.file.read to obtain the contents of abc.js.
Then use a regex to match the Boolean value assigned to the variable is_uglify.
Once the Boolean value for is_uglify is obtained then conditionally run either the registered Task named buildA or buildB using grunt.task.run
Gruntfile.js
The following gist shows how this can be achieved:
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
uglify: {
// ... <-- Define as necessary.
},
clean: {
build: {
//... <-- Define as necessary.
}
}
});
grunt.registerTask('getValue', 'Gets the value of a variable', function () {
var filepath = "path/to/abc.js", // <-- Define as necessary.
content = grunt.file.read(filepath),
value = content.match(/(?:var is_uglify = )(true|false);/);
if (!value) {
grunt.fail.warn(
'\'var is_uglify = [true|false];\' not found in: ' + filepath['yellow']
)
}
if (value[1] === 'true') {
grunt.task.run(['buildA']);
} else {
grunt.task.run(['buildB']);
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('build', ["getValue"]);
grunt.registerTask('buildA', ['clean:build','uglify']);
grunt.registerTask('buildB', ['clean:build']);
};
Additional Notes
In the following line of code the "path/to/abc.js" part will need to be redefined as per your directory structure. This must be the path to your file containing var is_uglify = ...;:
var filepath = "path/to/abc.js",
An explanation to the regex pattern /(?:var is_uglify = )(true|false);/ can be found here. It will find the first match only in abc.js.
The getValue Task/Function will warn if the is_uglify variable is missing and the Task/function simply fails and returns early.
After you have defined the configuration for the uglify and clean:build Task run $ grunt build via your CLI.

How to run code if yepnope returns true?

I use yepnope.js to load a polyfill (Intl). If window.Intl doesn't exist, it loads my polyfill, and executes some code. However, if windows.Intl does in fact exist, I need to execute another code, and I havn't been able to figure out how.
Here is what I have:
yepnope({
test : window.Intl,
nope : ['lib/Intl.min.js'],
callback: function(u,r,k){
$.ajax({
type: "GET",
url: 'sv-SE.json',
dataType: "json",
success: function(data) {
Intl.__addLocaleData(data,"sv-SE");
self.numberFormatter = new Intl.NumberFormat("sv-SE");
}
});
},
complete: function(){
/* Do stuff! */
The code I need to run if window.Intl already exists is self.numberFormatter = new Intl.NumberFormat("sv-SE");, but I can't figure out how, as callback is only called on false, as far as I can tell.

Mustache JS Template with JSON Collection

Hi this is my first attempt to use MustacheJS with a JSON webservice in .net
Currently I am struggling I can't seem to find what I am doing wrong setting this basic example:
My Webservice is returing the following string:
[
{
"ShortDescription":"BOX",
"Description":"BOXING",
"Id":1
},
{
"ShortDescription":"EPL",
"Description":"ENGLISH PREMIER LEAGUE",
"Id":2
}
]
I have validated its syntax with this website: http://json.parser.online.fr/
and here is the HTML code I am using:
google.load("jquery", "1");
google.setOnLoadCallback(function () {
$(document).ready(
function () {
$.ajax({
url: "../data.asmx/geteagues",
type: "POST",
dataType: "json",
data: "",
contentType: "application/json; charset=utf-8",
success: function (data) {
var template = "<h1>{{ShortDescription}} {{Description}}</h1>";
var html = Mustache.render(template, data);
$('#sampleArea').html(html);
alert(html);
}
})
}
)
});
I am posting the whole JS code, since I am not very good with javascript, basically I want to load always the latest JQuery version from google and then work my WS call.
The problem so far is that when I place a breakpoint in the following line:
var html = Mustache.render(template, data);
I see that the template is setn ok, and so does the data, same value as I posted above, but the .render function is returning: I seems It didnt like the data.
So far all the examples I have seen for inline data come as the following structure:
{
"repo": [
{ "name": "resque" },
{ "name": "hub" },
{ "name": "rip" },
]
}
And then a template defined like this:
{{#repo}}
<b>{{name}}</b>
{{/repo}}
But the only difference of that against my data is that I dont have a "parent" like "repo"
At server side, I am using a .net library called JSON.net and in the documentation of how are collections being serialized:
james.newtonking.com/projects/json/help/html/SerializingCollections.htm
the final result does not include the parent node's name, which I thing is missing from my Mustache Template definition:
[
{
"Name": "Product 1",
"ExpiryDate": "2000-12-29T00:00Z",
"Price": 99.95,
"Sizes": null
},
{
"Name": "Product 2",
"ExpiryDate": "2009-07-31T00:00Z",
"Price": 12.50,
"Sizes": null
}
]
Is this what I am missing? the "repo" parent node from my data so I can iterate my Template?
Thanks in advance for your time.
-ed
Per #stealth on this question Mustache.js: Iterate over a list received via json
{{ #. }}
<b>{{Name}}</b>
{{ /. }}
Note the only difference from #stealth's answer is a "#" instead of "/".
The line data = { 'roles': data }; is the most crucial. Its attaching the key to the data returned by web api or any other source of data like pagemethods or web service
$.ajax({
dataType: "json",
url: '/api/TestApi/GetAllRole',
success: function (data) {
data = { 'roles': data }; // formatting the data to support the mustache format
var html = Mustache.to_html($('#RoleTemplate').html(), data);
$('#tblRole').append(html);
}
});
Few of my articles on the MustacheJs can be found here
INLINE FILTER FOR BASIC GRID USING MUSTACHEJS
http://www.techguides.in/add-inline-filter-to-basic-grid-using-mustache/
Master Details Grid on Demand data loading : Using Mustache.JS
http://www.techguides.in/master-details-grid-on-demand-data-loading-using-mustache-js/
Sorting a Grid using MustacheJs
http://www.techguides.in/enable-sorting-in-a-grid-bound-using-mustache-js/
short answer: YES
long answer: for security reasons [1], you need to wrap your JSON aray in an object anyways. for Mustache or any other library to be able to access your array you need to have at least one parent key on which you can base your iterator.
The "repo" key on your sample is the helper you need to tell mustache "go and iterate on the array that is inside the repo key", otherwise you have no way to tell the template what you want to output where
[1] this is just one of many resources you can find about why you need to wrap your JSON response in an object http://incompleteness.me/blog/2007/03/05/json-is-not-as-safe-as-people-think-it-is/

Resources