fine-uploader trouble with formatting the code, events - javascript

I need to have multiple events associated with the fineuploader instantiation, but I'm not sure how to go about it. Can't they be added within the fineuploader properties, etc.? Isn't the complete event then called onComplete? Is there an example that exists? Also, I'm confused about the number of closing brackets, etc. When I originally cut and pasted this code in, there was an extra )}; that sat outside. I removed that, but I'm not sure if that's cool or not for the actual code. Any help is appreciated, as I've been toying with this for hours. Some variables have been set outside this code.
$(document).ready(function () {
var controlType = '#Model.ControlType';
var surveyItemResultId = #Model.Results[0].SurveyItemResultId;
var itemId = #Model.SurveyItemId;
var instance = #Model.Results[0].SurveyInstanceID;
var loopingCounter = 0;
var fineuploader = $('#files-upload').fineUploader({
request:
{
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
loopingIndex: (function () { return loopingCounter++; })
}
},
validation: {
acceptFiles: ['image/*','application/pdf','text/csv'] ,
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'csv', 'pdf'],
sizeLimit: 1024*1024*1 // 1MB
},
multiple: true,
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Select your upload file(s)'
}
})
.on('complete', function(event, id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
uploadedFileCounter++;
if (filesToUpload == uploadedFileCounter)
{
alert("DONE UPLOADING!");
}
}).on('submitted', function(event, id, filename) {
filesToUpload++;
alert("submitted: " + filesToUpload);
}
});
});

Your code is littered with syntax and other errors. First off, you are referencing filesToUpload and uploadedFileCounter variables that are not defined anywhere in your code. Second, you have an extra closing bracket in your code.
There are also some formating issues with your code. First, Your code is inconsistently indented. Second, you are mixing placement of curly brackets.
Here is your original code with my adjustments:
$(document).ready(function () {
var controlType = '#Model.ControlType',
surveyItemResultId = #Model.Results[0].SurveyItemResultId,
itemId = #Model.SurveyItemId,
instance = #Model.Results[0].SurveyInstanceID,
loopingCounter = 0,
filesToUpload = 0,
uploadedFileCounter = 0;
var fineuploader = $('#files-upload').fineUploader({
request: {
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
loopingIndex: (function () { return loopingCounter++; })
}
},
validation: {
acceptFiles: ['image/*','application/pdf','text/csv'] ,
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'csv', 'pdf'],
sizeLimit: 1024*1024*1 // 1MB
},
multiple: true,
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Select your upload file(s)'
}
})
.on('complete', function(event, id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
uploadedFileCounter++;
if (filesToUpload == uploadedFileCounter) {
alert("DONE UPLOADING!");
}
}).on('submitted', function(event, id, filename) {
filesToUpload++;
alert("submitted: " + filesToUpload);
});
});

Related

Fancy tree: How to call two endpoint according to result

I am using fancy tree in my application UI:
f_tree = $("#nodes_tree").fancytree({
extensions: ["table"],
table: {
indentation: 24,
nodeColumnIdx: 0
},
source: [
{
title: "/",
key: "jcr:root",
folder: true,
lazy: true,
}
],
lazyLoad: function (event, data) {
let node = data.node;
let path = buildPath(node);
if (path !== '/') {
data.result = {
url: 'http://localHost:8080/getDetails'
};
} else {
data.result = elasticResponse;
}
},
postProcess: function (event, data) {
if (data.response) {
data.result = data.response._paths;
}
},
renderColumns: function (event, data) {
let d = data.node.data,
$tdList = $(data.node.tr).find(">td");
if (d.attributes) {
//console.info(`step 333`);
$tdList.eq(1).text(d.attributes['title'])
}
}
});
I am not able to write condition, if "http://localHost:8080/getDetails/1234" will return {} blank json response instead of {"_paths":[{"title":"..."}]"} response then it should call another url i.e; "http://localHost:8087/getAnotherDetails/1234". Please let me know how I can achieve this in fancy tree.

UIKIT 3 get the name of the file been uploaded

I try to create a function where the user uploads the file and then showing the image that's been uploaded to a div. But I need to have the name of the file in order to add the src attr to
Seems like UIKIT 3 does not have a way where I can get the name of the file when it's dropped or selected.
Anyone can help this, please?
Here's the code from UIKIT, and here's the docs they provide
UIkit.upload('.js-upload', {
url: '../config/forms.php',
beforeSend: function () {
console.log('beforeSend', arguments);
},
beforeAll: function () {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function () {
console.log('error', arguments);
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (arguments) {
console.log('completeAll', arguments);
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
}
});
JS side:
UIkit.upload('.js-upload', {
url: 'file_upload.php',
multiple: false,
mime: "image/*",
completeAll: function () {
uploaded_filename = arguments[0].response;
}
});
PHP Side:
$uploads_dir = PUBLIC_FOLDER."uploads";
$tmp_name = $_FILES['form-drop-place']['tmp_name'];
$image_name = $_FILES['form-drop-place']['name'];
$ext = pathinfo($image_name, PATHINFO_EXTENSION);
$new_name = "newname." . $ext;
$new_place = $uploads_dir . "/" . $new_name;
if ( move_uploaded_file($tmp_name, $new_place) ) {
die($new_name);
} else {
die();
}

Add Custom JS and CSS Files to Custom Yeoman Generator

I'm trying to build a custom yeoman generator and I'm basing if off of the webapp generator from yeoman. I'm need to know how to add certain js and css files if bootstrap is not selected. These files are currently being stored at the same level as my index.html file along with main.css.
I've tested the generator and everything works just fine, I just can't figure out how to add certain files or exclude them if bootstrap is present. Any help is greatly appreciated.
Please ask a question before a down vote. This is the first time I've messed with a custom generator.
Below is my index.js file:
'use strict';
var join = require('path').join;
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
module.exports = yeoman.generators.Base.extend({
constructor: function () {
yeoman.generators.Base.apply(this, arguments);
// setup the test-framework property, Gruntfile template will need this
this.option('test-framework', {
desc: 'Test framework to be invoked',
type: String,
defaults: 'mocha'
});
this.testFramework = this.options['test-framework'];
this.option('coffee', {
desc: 'Use CoffeeScript',
type: Boolean,
defaults: false
});
this.coffee = this.options.coffee;
this.pkg = require('../package.json');
},
askFor: function () {
var done = this.async();
// welcome message
if (!this.options['skip-welcome-message']) {
this.log(require('yosay')());
this.log(chalk.magenta(
'Out of the box I include HTML5 Boilerplate, jQuery, and a ' +
'Gruntfile.js to build your app.'
));
}
var prompts = [{
type: 'checkbox',
name: 'features',
message: 'What more would you like?',
choices: [{
name: 'Bootstrap',
value: 'includeBootstrap',
checked: true
},{
name: 'Sass',
value: 'includeSass',
checked: false
},{
name: 'Modernizr',
value: 'includeModernizr',
checked: false
}]
}, {
when: function (answers) {
return answers && answers.feature &&
answers.features.indexOf('includeSass') !== -1;
},
type: 'confirm',
name: 'libsass',
value: 'includeLibSass',
message: 'Would you like to use libsass? Read up more at \n' +
chalk.green('https://github.com/andrew/node-sass#node-sass'),
default: false
}];
this.prompt(prompts, function (answers) {
var features = answers.features;
function hasFeature(feat) {
return features && features.indexOf(feat) !== -1;
}
this.includeSass = hasFeature('includeSass');
this.includeBootstrap = hasFeature('includeBootstrap');
this.includeModernizr = hasFeature('includeModernizr');
this.includeLibSass = answers.libsass;
this.includeRubySass = !answers.libsass;
done();
}.bind(this));
},
gruntfile: function () {
this.template('Gruntfile.js');
},
packageJSON: function () {
this.template('_package.json', 'package.json');
},
git: function () {
this.template('gitignore', '.gitignore');
this.copy('gitattributes', '.gitattributes');
},
bower: function () {
var bower = {
name: this._.slugify(this.appname),
private: true,
dependencies: {}
};
if (this.includeBootstrap) {
var bs = 'bootstrap' + (this.includeSass ? '-sass-official' : '');
bower.dependencies[bs] = "~3.2.0";
} else {
bower.dependencies.jquery = "~1.11.1";
}
if (this.includeModernizr) {
bower.dependencies.modernizr = "~2.8.2";
}
this.write('bower.json', JSON.stringify(bower, null, 2));
},
jshint: function () {
this.copy('jshintrc', '.jshintrc');
},
editorConfig: function () {
this.copy('editorconfig', '.editorconfig');
},
mainStylesheet: function () {
var css = 'main.' + (this.includeSass ? 's' : '') + 'css';
this.template(css, 'app/styles/' + css);
// Add imod-grid.css
var imod = 'imod-grid.' + 'css';
this.template(imod, 'app/styles/' + imod);
},
writeIndex: function () {
this.indexFile = this.engine(
this.readFileAsString(join(this.sourceRoot(), 'index.html')),
this
);
// wire Bootstrap plugins
if (this.includeBootstrap && !this.includeSass) {
var bs = 'bower_components/bootstrap/js/';
this.indexFile = this.appendFiles({
html: this.indexFile,
fileType: 'js',
optimizedPath: 'scripts/plugins.js',
sourceFileList: [
bs + 'affix.js',
bs + 'alert.js',
bs + 'dropdown.js',
bs + 'tooltip.js',
bs + 'modal.js',
bs + 'transition.js',
bs + 'button.js',
bs + 'popover.js',
bs + 'carousel.js',
bs + 'scrollspy.js',
bs + 'collapse.js',
bs + 'tab.js'
],
searchPath: '.'
});
}
this.indexFile = this.appendFiles({
html: this.indexFile,
fileType: 'js',
optimizedPath: 'scripts/main.js',
sourceFileList: ['scripts/main.js'],
searchPath: ['app', '.tmp']
});
},
app: function () {
this.directory('app');
this.mkdir('app/scripts');
this.mkdir('app/styles');
this.mkdir('app/images');
this.write('app/index.html', this.indexFile);
if (this.coffee) {
this.write(
'app/scripts/main.coffee',
'console.log "\'Allo from CoffeeScript!"'
);
}
else {
this.write('app/scripts/main.js', 'console.log(\'\\\'Allo \\\'Allo!\');');
}
},
install: function () {
this.on('end', function () {
this.invoke(this.options['test-framework'], {
options: {
'skip-message': this.options['skip-install-message'],
'skip-install': this.options['skip-install'],
'coffee': this.options.coffee
}
});
if (!this.options['skip-install']) {
this.installDependencies({
skipMessage: this.options['skip-install-message'],
skipInstall: this.options['skip-install']
});
}
});
}
});

Backbone View: function is undefined

I want to build a simple backbone app for depositing and withdrawing funds via Stripe. Since a lot of the functionality is common, I placed that in a Stripe view, and extend the Deposit and Withdraw views from it, like so:
var App = {
Models: {},
Collections: {},
Views: {},
Router: {}
}
App.Views.Home = Backbone.View.extend({
el: $('#main-content'),
template: Handlebars.compile($('#home-template').html()),
render: function() {
this.$el.html(this.template())
return this
},
events: {
'click #deposit-button': 'navigateToDeposit',
'click #withdraw-button': 'navigateToWithdraw'
},
navigateToDeposit: function(e) {
Backbone.history.navigate('/deposit', true)
},
navigateToWithdraw: function(e) {
Backbone.history.navigate('/withdraw', true)
}
})
App.Views.Stripe = Backbone.View.extend({
el: $('#main-content'),
initialize: function() {
Stripe.setPublishableKey('pk_test_0QvQdPBkXAjB4EBsT4mf226x')
},
render: function() {
this.$el.html(this.template())
return this
},
events: {
'click #submit': 'submitForm'
},
submitForm: function(e) {
e.preventDefault()
$('#submit').prop('disabled', true)
var that = this
Stripe.card.createToken($('#form'), that.stripeResponseHandler)
},
stripeResponseHandler: function(status, response) {
var $form = $('#form')
if(response.error) {
$form.find('.payment-errors').text(response.error.message)
$('submit').prop('disabled', false)
} else {
console.log(this)
var form_data = this.getFormData(response.id),
that = this
$.post(that.transaction_endpoint, form_data, function(data, textStatus, jqXHR) {
Backbone.history.navigate('/home', true)
})
}
}
})
App.Views.Deposit = App.Views.Stripe.extend({
template: Handlebars.compile($('#deposit-template').html()),
getFormData: function(token) {
return {
amount: $('#form input[name=amount]').val(),
token: token
}
},
transaction_endpoint: 'handledeposit'
})
App.Views.Withdraw = App.Views.Stripe.extend({
template: Handlebars.compile($('#withdraw-template').html()),
getFormData: function(token) {
return {
name: $('#form input[name=name]').val(),
email: $('#form input[name=email]').val(),
token: token
}
},
transaction_endpoint: 'handlewithdraw'
})
App.Router = Backbone.Router.extend({
routes: {
'deposit' : 'showDepositView',
'withdraw' : 'showWithdrawView',
'*path' : 'showHomeView'
},
showDepositView: function() {
var depositView = new App.Views.Deposit()
depositView.render()
},
showWithdrawView: function() {
var withdrawView = new App.Views.Withdraw()
withdrawView.render()
},
showHomeView: function() {
var homeView = new App.Views.Home()
homeView.render()
}
})
var router = new App.Router()
Backbone.history.start()
The call to the getFormData method gives me an error saying the function is undefined, even though I have defined it in both Deposit and Withdraw views. Also, I added a console.log(this) right above it, and it logs the Window object to the console instead of the View. What am I doing wrong here?
I have a feeling it's to do with this call:
Stripe.card.createToken($('#form'), that.stripeResponseHandler)
Try binding this to the calling scope using .bind():
Stripe.card.createToken($('#form'), that.stripeResponseHandler.bind(this))
You don't really need to do var that = this but I'll leave it in for simplicity's sake.

What is the difference between plug-in-type methods and methods in a global variable

In terms of efficiency,
what's the fastest and most standard way to tweak a function in javascript?
Plugin-style coding would be like this.
; (function ($, window, document, undefined) {
var pluginName = "SoketManager",
dataPlugin = "plugin_" + pluginName,
settings = {
target: this,
width: 350,
height: 150,
theme: 'default'
}
var Plugin = {
// instance...
}
Plugin.prototype = {
connect: function() {
//something.
},
disconnect: function() {
//something.
},
sendmessage: function() {
//something...
},
etc: function() {
}
//etc2: function() .......
}
$.fn[pluginName] = function (arg, contents) {
var args, instance;
if (typeof arg === 'string' && typeof instance[arg] === 'function') {
args = Array.prototype.slice.call(arguments, 1);
return instance[arg].apply(instance, args);
}
And using global variable would be like this..
var SocketManager = {
sock: '',
connect: function () {
var stdInfo = new JSONClientParameters();
var socket = io.connect('http://192.168.1.39:3000', {
query: stdInfo.toGetString()
//'reconnect': true,
// 'reconnection delay': 500,//default 500
//'max reconnection attempts': 10
});
kdbSocketManager.ksock = socket;
socket.on('connect', function () {
alert('successfully connected to the database!!');
});
},
disconnect: function () {
this.ksock.disconnect();
},
sendMessage: function (pMsg, pTargetId) {
this.ksock.emit('sendMessage', { msg: pMsg, targetId: pTargetId });
},
I see no point in coding like the plugin-way. Is it much more simple and easy to read to code like the latter one? could somebody explain this in detail?

Categories