Using FineUploader ( http://docs.fineuploader.com/branch/master/api/callbacks.html ) -- all my code works perfectly, with the exception of the onComplete callback. Simply doesn't fire - can't see what I might be doing wrong, have even used a copy/paste version from the demo. I have also tried a "jquery" style of setting this up, again with no console.log() output on complete.
function createUploader() {
var uploader = new qq.FileUploader({
element: document.getElementById('fine-uploader'),
// Use the relevant server script url here
action: '/admin/upload',
debug: true,
callbacks: {
onComplete: function(id, fileName, responseJSON) {
console.log('response');
if (responseJSON.success) {
console.log('success');
//$('#thumbnail-fine-uploader').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
}
}
});
}
window.onload = createUploader;
EDIT: Firebug does not throw any errors for this; syntax is correct
Echoing #meltner, you are following documentation for a current version of Fine Uploader and applying this to a very old version of the library. The API changed in several breaking ways starting with version 3.0. One change included a move of all callbacks to a callbacks option. Another included a change from FileUploader to FineUploader. The version you are using is definitely pre-3.0. Consider upgrading at http://fineuploader.com.
Related
I have created a code that it actually works, but I call a library that has an error, and I would like to know if it is possible to avoid that specific line of code. I will try to explain the case as well as possible:
Error
Uncaught TypeError: fs.openSync is not a function
Previous code
function synthesizeToAudioFile(authorizationToken, message) {
// replace with your own subscription key,
// service region (e.g., "westus"), and
// the name of the file you save the synthesized audio.
var serviceRegion = "westus"; // e.g., "westus"
var filename = "./audiocue.wav";
//Use token.Otherwise use the provided subscription key
var audioConfig, speechConfig;
audioConfig = SpeechSDK.AudioConfig.fromAudioFileOutput(filename);
speechConfig = SpeechSDK.SpeechConfig.fromAuthorizationToken(authorizationToken, serviceRegion);
// create the speech synthesizer.
var synthesizer = new SpeechSDK.SpeechSynthesizer(speechConfig, audioConfig);
// start the synthesizer and wait for a result.
synthesizer.speakTextAsync(message,
function (result) {
if (result.reason === SpeechSDK.ResultReason.SynthesizingAudioCompleted) {
console.log("synthesis finished.");
} else {
console.error("Speech synthesis canceled, " + result.errorDetails +
"\nDid you update the subscription info?");
}
synthesizer.close();
synthesizer = undefined;
},
function (err) {
console.trace("err - " + err);
synthesizer.close();
synthesizer = undefined;
});
console.log("Now synthesizing to: " + filename);
}
I created a method, which later I have replicated in my current code. The difference was that I was using Browserify in order to import a library from a script of a HTML file:
<script type="text/javascript" src="js/dist/sub_mqtt.js"></script>
This file had my method, and the whole library, which made it crazy unreadable, and therefore I started using ScriptJS to import it. The problem is that, using browserify I was able to remove the line of code that it was failing using fs.openSync(and I do not even need), but by importing it with ScriptJS I do not have access to the source code.
I assume that what is missing is that I am not importing the library fs, which is being used by the library that I am importing with ScriptJS before importing that one, but how could I do it? I have tried:
<script src="../text-to-speech/node_modules/fs.realpath/index.js"></script>
, or
<script type="text/javascript" src="../text-to-speech/node_modules/fs.realpath/index.js"></script>
and also wrapping the content of synthesizeToAudioFile() with
require(["node_modules/fs.realpath/index.js"], function (fs) { });
but I get the following error:
Uncaught ReferenceError: module is not defined
at index.js:1
After researching about this question I found out the next statement:
The fs package on npm was empty and didn't do anything, however many
packages mistakenly depended on it. npm, Inc. has taken ownership of
it.
It's also a built-in Node module. If you've depended on fs, you can
safely remove it from your package dependencies.
therefore what I have done is to access to the file that I was requiring with ScriptJS
require(["../text-to-speech/microsoft.cognitiveservices.speech.sdk.bundle.js"]
and directly remove that line on it. Note that, at least in my case, clearing the cache of the browser was needed.
If my Jasmine test has failures, it only shows those by default. I have to click "Spec List" to see all of the tests that were run.
Can I somehow get it to always show the spec list by default?
I am using jasmine 2.1.3 with require.js as outlined in this stackoverflow question:
Getting requirejs to work with Jasmine
and this was bugging me too.
I am also using jquery so I added an event trigger after the .execute() like so:
require(specs, function (spec) {
jasmineEnv.execute();
$('.spec-list-menu').click();
});
I couldn't find any configuration for setting the default, but you can see in the jasmine-html.js file:
find('.failures-menu').onclick = function() {
setMenuModeTo('failure-list');
};
find('.spec-list-menu').onclick = function() {
setMenuModeTo('spec-list');
};
setMenuModeTo('failure-list');
if you changed it to:
find('.failures-menu').onclick = function() {
setMenuModeTo('failure-list');
};
find('.spec-list-menu').onclick = function() {
setMenuModeTo('spec-list');
};
setMenuModeTo('spec-list');
It will also set the default.
I don't really like editing libraries like that since I usually forget what I have changed when I update the library.
That was the reason I went with the jquery route.
I am starting to play with require js / modular development for the first time and am liking what I see.
What I am trying to achieve is basically only load certain custom jQ modules when needed. My main goal is page performance. At present I am only loading require.js (which in turns loads jQ async) then other jQ code/plugins only fire on user interaction.
Would the following code be considered good/bad practice? Is there anything anyone would change? (super basic example below)
MAIN.JS
require.config({
paths: {
"jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min"
}
});
require(["jquery"], function($) {
// overlay plugin
$("a").on("click", function(e){
var self = this;
require(["overlay"], function (overlay) {
overlay.init(self);
});
e.preventDefault();
});
});
OVERLAY.JS
define(function () {
return {
init: function(self) {
$.ajax({
url: self.href,
success: function (data) {
$("#results").html($(data).filter('#details').html());
},
dataType: 'html'
});
$('#results').fadeIn();
}
}
});
Cheers,
Adi.
Your method of loading overlay is a correct use of require, however a couple of things:
Overlay.js should list jQuery as a dependency. Ensure your modules have all the code they need to run. In this case it's fine (as you're grabbing jQuery in the require) but say you used document.addEventListener to attach your click then you're no longer sure jQuery will be available for use by the $.ajax. It's nice to know your modules ask for everything they need rather than getting it by luck.
One rule I try to follow is to keep all my DOM related stuff in main. So for example:
Overlay
// Example code, and not complete
define(function(require) {
var $ = require('jquery');
return {
init: function(elements) {
this.trigger = $(elements.trigger);
this.target = $(elements.target);
this.trigger.on('click', this.someEvent.bind(this));
},
someEvent: function() {
this.getAjax();
}
}
});
And then in main.js just pass in the DOM elements
require(['overlay'], function(overlay) {
overlay.init({
trigger: 'a',
target: '#results'
})
});
Keeping the DOM elements separate and in one place makes updating them breeze. You could also pass in an options object for other things (such as class names) much like a jQuery plugin does.
Finally, in your example code your $('#results').fadeIn(); is outside the success callback and would run immediately.
I have a problem with creating a tool that's provides a custom overlay on a page via a code generation plugin that is grabbed from the server once the user clicks a bookmarklet on an external site.
When calling $.getScript inside the bookmarklet, the bookmarklet gets the script successfully and starts executing the callback function. Everything is working until I start accessing the plugin itself to start generating the HTML. However, once the plugin method is called, I am unable to receive anything from console, and the overlay fails to appear.
Plugin structure (source for methods themselves omitted as it's a company project - unfortunate, I'm aware, but sadly necessary).:
(function(jQuery){
var methods = {
generateHeader : function () {
},
generateItem : function(arguments) {
},
generateGridList : function(arguments) {
},
hideOverlay : function(){
}
}
jQuery.fn.generator = function(method) {
console.log("generator reached"); //Doesn't print.
if(methods[method]){
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method[method] === 'object' || !method){
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.generator');
}
};
})( jQuery );
And my relevant bookmarklet contents:
$.getScript(<scriptURL>, function() {
//generate data to send to server
//send unordered lists to server for processing
$.ajax({
requestType:'GET',
url: <url>,
dataType: 'jsonp',
jsonp: 'callback',
success: function(returnedData){
//success param inside as data is required to proceed.
$.each(returnedData.data, function(i, val){
var htmlToAdd,
content;
console.log(val); //succeeeds, not null.
htmlToAdd = $.generator('generateItem', val);
console.log(htmlToAdd); //fails to reach log at this point
//code to append to page
});
}
});
});
All the methods do is generate HTML and CSS based on $.css and $(), var.append() and var.html() functions, and a couple of hide/remove functions to clear it on exit.
It's late here (close to 9:30pm as of posting) and I'm losing concentration, so I'll be double checking the methods when I arrive in the office tomorrow morning, I just wanted clarification on any pitfalls this approach has, or if I have any glaring mistakes in my AJAX request, my use of getScript() or my plugin structure. If I know it's likely to be a method based issue, that narrows my search and allows for a potential rewrite of certain functions.
Thanks in advance,
Craig Domville.
I just wanted clarification on any pitfalls this approach has, or if I have any glaring mistakes in my AJAX request, my use of getScript() or my plugin structure.
I see nothing wrong with your basic approach.
Some things to consider: Before you use $.generator(...), add console.log($.generator) and see if it returns the function code you expect. Don't assume that just because getScript callback fired, that script was executed properly. You seem to assume that $ == jQuery; maybe that is a safe assumption, maybe not.
This has had me puzzled for a few hours now. When the script is in a non-requirejs javascript file it works fine. When I use it with RequireJS it fails to work and gives me the error messages in the question title (though the firebug console).
I was just trying to get it to "work" with RequireJS before attempting to refactor into a module.
The Html is rendering correctly. The scripts are loading correctly. Also, I'm using the require-jquery.js bundle download, which is referenced in the layout template across all pages.
main.js:
require.config({
paths: {
"maximum-filesize": "modules/validation/maximum-filesize"
}
});
require(["maximum-filesize", "domReady!"], function (maxFileSize) {
});
maximum-filesize.js
require.config({
paths: {
"jquery-validate": "libs/jquery/jquery.validate",
"jquery-validate-unobtrusive": "libs/jquery/jquery.validate.unobtrusive"
}
});
define(["jquery", "jquery-validate", "jquery-validate-unobtrusive", "domReady!"], function ($) {
$.validator.unobtrusive.adapters.add(
'filesize', ['maxsize'], function(options) {
options.rules['filesize'] = options.params;
if (options.messages) {
options.messages['filesize'] = options.message;
}
});
$.validator.addMethod('filesize', function (value, element, params) {
if (element.files.length < 1) {
// No files selected
return true;
}
if (!element.files || !element.files[0].size) {
// This browser doesn't support the HTML5 API
return true;
}
return element.files[0].size < params.maxsize;
}, '');
});
Edit 1
I just tried commenting out all of the above code, and replaced it with a simple:
$('#Name').val("Hello");
This rendered "Hello" correctly in the #Name textbox, so JQuery is working.
You should use requires shim option to tell requires to load jquery before jquery validate. Otherwise load order is undefined.
Another possible problem is calling requirejs.config 2 times. Requirejs has problems with merging configs