RequireJS - Issues properly loading ko.editables.js - javascript

Im new to requirejs and loving it so far. I have it working juste fine with knockout js. I then introduced a plugins called ko.editables (https://github.com/romanych/ko.editables) that would allow to undo changes very easily.
I added the path on in my equirejs config file so that ko.editables has knockout as it's dependency. In my knockout application code I defined knockout and then ko.editables and the files (knockout.js and ko.editables.js) are loading correctly from what I can see in my crome console sources.
Here is my requirejs config file:
require.config({
baseUrl: './js',
paths: {
"ko_editables": "ko.editables"
},
"shim": {
ko_editables: {
deps : [ 'knockout' ]
}
}
});
This is my application code I have that controls my knockout view model.
define(["knockout", "ko_editables"], function(ko, editables) {
... I hide some code here just to show the ko.editable functions im using.
self.Edit = function (incident) {
var CurrentEdititngIncident = self.EditingIncident();
if (CurrentEdititngIncident && CurrentEdititngIncident != incident) {
if (CurrentEdititngIncident.hasChanges()) {
if (confirm('Your have unsaved changes. Press Ok to cancel these changes. Press Cancel to continue editing')) {
CurrentEdititngIncident.rollback();
} else {
return;
}
};
}
ko.editable(incident);
incident.beginEdit();
self.EditingIncident(incident);
self.showDialog(true);
};
self.SaveorUpdate = function (incident) {
var id = this.ID,
self.EditingIncident().commit();
url = Incident.BASE_URL + (id ? '(' + encodeURIComponent(id) + ')' : '');
return $.ajax(url, {
type: id ? "MERGE" : "POST",
data: ko.toJSON({
Description: this.Description,
Incident: this.Incident
}),
processData: false,
contentType: "application/json;odata=verbose",
headers: id ? Incident.UPDATE_HEADERS : Incident.CREATE_HEADERS,
success: function (incident) {
self.showDialog(false);
self.EditingIncident(undefined);
console.log("Record was sucessfully saved.");
}
});
... I hide some code here just to show the ko.editable functions im using.
};
I created a version without requirejs in a jsfiddle to demonstrate that the same code works without requirejs. So im not quite sure what ut us that im missing. I went trough the website https://github.com/romanych/ko.editables and it mentions that its AMD compatible but cant find info on how to properly load it.
Hoping that some people are familiar with requirejs or with ko.editables. Would anyone have any ideas?

Related

Cannot find name 'jQuery' error in controller.js

I am developing a UI5 app in VS Code.
I added a new count function to the *.controller.js file, and in order to display the count from the server, I am using jQuery like in the following code:
jQuery.each(this._mFilters, function (sFilterKey, oFilter) {
oModel.read("/portfolios/$count", {
filters: oFilter,
success: function (oData) {
var sPath = "/" + sFilterKey;
oViewModel.setProperty(sPath, oData);
}
});
});
Unfortunately, I get the following error:
Does anyone know why was the error triggered and how it can be fixed?
Any help or suggestion is much appreciated.
I assume this._mFilters is an object. In that case, try with:
Object.keys(this._mFilters).map(sFilterKey => {
const oFilter = this._mFilters[sFilterKey];
oModel.read("/portfolios/$count", {
filters: [ oFilter ],
success: function(sCount) {
const sPath = `/${sFilterKey}`;
oViewModel.setProperty(sPath, +sCount);
},
});
});
Also the parameter filters awaits an array instead of a single Filter instance.
If jQuery is still preferred, include "sap/ui/thirdparty/jquery" (formerly "jquery.sap.global") to the dependency list of the controller.
sap.ui.define([
"sap/ui/core/mvc/Controller",
// ...,
"sap/ui/thirdparty/jquery",
], function(Controller,/*...,*/ jQuery) {
// jQuery is here available
});

autoComplete.js - how to resolve autoComplete is not defined

I want to use autocomplete.js in my application.
I have installed the package using yarn add #tarekraafat/autocomplete.js. I am using webpack 4.28 to bundle the javascript files and have require("#tarekraafat/autocomplete.js/dist/js/autoComplete"); to import the package into the application and placed the bundled file at the bottom before the closing BODY tag.
In my custom.js file, I am creating a new instance of autoComplete as follows:
new autoComplete({
data: {
src: async () => {
document.querySelector("#autoComplete_results_list").style.display = "none";
document.querySelector("#autoComplete").setAttribute("placeholder", "Loading...");
const source = await fetch("/employee/search");
const data = await source.json();
return data;
},
key: "name"
},
selector: "#autoComplete",
placeHolder: "type employee name to search...",
threshold: 0,
searchEngine: "strict",
highlight: true,
dataAttribute: { tag: "value", value: "" },
maxResults: Infinity,
renderResults: {
destination: document.querySelector("#autoComplete"),
position: "afterend"
},
onSelection: feedback => {
document.querySelector(".selection").innerHTML = feedback.selection.food;
document
.querySelector("#autoComplete")
.setAttribute("placeholder", `${event.target.closest(".autoComplete_result").id}`);
console.log(feedback);
}
});
However, on running the application, I am getting an error Uncaught ReferenceError: autoComplete is not defined with a reference to the location where I am creating the new instance.
I have read the getting started documentation and looked at the demo code and I can't figure out what I am missing. How do I resolve the error?
Your problem is in your import, you are not import the autoComplete correctly, so when you using the new autoComplete you are having error.
Change the require("#tarekraafat/autocomplete.js/dist/js/autoComplete"); to import autoComplete from '#tarekraafat/autocomplete.js';, put this on top of your file, right after jquery or something
Write your code inside
$(document).ready(function(){
// Write your Code Here
});

Jaspersoft visualise.js report export failing to produce file

I hope there is few among you who have experience with Jaspersoft Reports and their new visualise.js api
I have a problem with visualise.js not producing report export file. What happens is:
I am able to succsefully load the report through the visualise.js API, it loads and displays on my web page
Export controls load up successfully too, so I have dropdown with export file formats and a button to export the file.
When I click the export button though, the whole page reloads as if the export button was really a submit button and nothing happens.
Occasionally, the export will work and it will produce file. Though there is no pattern to when it will produce the file and when it will fail.
Below is the code I am using for this (I am using plain text auth for testing purposes):
visualize({
auth: {
name: "mylogin",
password: "mypass",
organization: "organization_1"
}
}, function (v) {
var $select = buildControl("Export to: ", v.report.exportFormats),
$button = $("#button"),
report = v.report({
resource: "/FPSReports/journal",
container: "#export",
params: {
"journal_ref": [ "<?php echo $reference; ?>" ],
},
success: function () {
button.removeAttribute("disabled");
},
error : function (error) {
console.log(error);
}
});
$button.click(function () {
console.log($select.val());
report.export({
// export options here
outputFormat: $select.val(),
// exports all pages if not specified
// pages: "1-2"
}, function (link) {
var url = link.href ? link.href : link;
window.location.href = url;
}, function (error) {
console.log(error);
});
});
function buildControl(name, options){
function buildOptions(options) {
var template = "<option>{value}</option>";
return options.reduce(function (memo, option) {
return memo + template.replace("{value}", option);
}, "")
}
var template = "<label>{label}</label><select>{options}</select><br />",
content = template.replace("{label}", name)
.replace("{options}", buildOptions(options));
var $control = $(content);
$control.insertBefore($("#button"));
//return select
return $($control[1]);
}
});
HTML:
<div class="grid">
<div class="grid-8"></div>
<div class="grid-8 center">Export</div>
<div class="grid-8"></div>
</div>
<div class="grid">
<div class="grid-24" id="export"></div>
</div>
The only parameter comes from URI segment (I am using codeigniter framework):
$reference = $this->uri->segment(3, 0);
I have found an answer that seems to work, and has resolved the issue. Posting it here in case anyone else has this specific problem like I did.
In brief:
After spending hours looking at console debug output I have realised that each time I tried to send a request for export a new session would be opened. Without logging out of the previous one. And apparently that is a no-no. I do not know JS very well but from what I understood there was session id mismatch in request. Please feel free to correct me here :)
The solution to this problem (or for example if you are having authentication issues with visualize.js) is very simple. Set the authentication in global config:
visualize.config({
auth: {
name: "superuser",
password: "superuser"
}
});
No matter if you are using tokens or plain text or whatever else auth is available through the api.
Then do your stuff wherever else on your website:
visualize(function (v) {
v("#container1").report({
resource: "/public/Samples/Reports/06g.ProfitDetailReport",
error: function (err) {
alert(err.message);
}
});
});
visualize(function (v) {
v("#container2").report({
resource: "/public/Samples/Reports/State_Performance",
error: function (err) {
alert(err.message);
}
});
});
Everything should work for you as it did for me. This works in version 5.6 and 6.1 of visualize.js.
Further reading and links from my research:
Token based authentication to Jasper reports failing when used with visualize.js
Visualize.js authentication error after second login
http://community.jaspersoft.com/questions/842695/visualizejs-authentication-error
http://community.jaspersoft.com/questions/845886/authentication-error-refresh-credentials-visualizejs
Code example (5.6):
http://jsfiddle.net/TIBCO_JS_Community/sozzq0sL/embedded/
Api samples (6.1):
http://community.jaspersoft.com/wiki/visualizejs-api-samples-v61
Api samples (5.6):
http://community.jaspersoft.com/wiki/visualizejs-api-notes-and-samples-v56
Really hope this will help someone new to Jaspersoft & visualize.js like me.

Plupload: perform custom check before starting upload

I have an MVC 5 view with a form and a plupload file uploader section. Upload is triggered by a button on the form. I have no problem uploading file chunks to the server and setting the parameters to the query string and all, but what I do have a problem with is starting the upload only after a custom sanity check has been performed.
Here's what I have tried:
var uploader = new plupload.Uploader({
runtimes: 'html5',
drop_element: 'upload',
browse_button: 'browse',
url: "../UploadFile",
chunk_size: "1024kb",
multipart_params: { "uid": "uid", "chunk": "chunk", "chunks": "chunks", "name": "name" },
init: {
PostInit: function(file) {
document.getElementById("filelist").innerHTML = "";
document.getElementById('submit-all').onclick = function () {
document.getElementById("infoPopup").style.visibility = "visible";
document.getElementById('submit-all').enabled = false;
var uuid = Math.uuidFast();
document.getElementById("uid").value = uuid;
uploader.settings.multipart_params = { uid: uuid, chunk: file.chunk, chunks: file.chunks, name: file.name };
if (checkReq) {
uploader.start();
}
return false;
};
},
The crucial part here is this:
if(checkReq){
uploader.start();
}
"checkReq" is my custom sanity check script that verifies that form values are not nonsensical (e.g. single form entries might be perfectly valid while in combination they are simply wrong, etc.).
So the above does not prevent the upload, the check script is not even fired, Firebug console output shows no error.
Since googling tells me that there is also a "BeforeUpload" event, I tried this:
BeforeUpload: function(up, file) {
if (checkReq) {
up.stop();
return false;
}
return true;
},
Which also does not seem to fire at all.
Edit: Next attempt, I put the call to my checkReq fuction into BeforeUpload in "preinit", which should fire before any chunking etc is done, so before the upload is prepared. This also failed although I have no idea why it does not fire:
var uploader = new plupload.Uploader({
runtimes: 'html5',
drop_element: 'upload',
browse_button: 'browse',
url: "../UploadFile",
chunk_size: "1024kb",
multipart_params: { "uid": "uid", "chunk": "chunk", "chunks": "chunks", "name": "name" },
preinit: {
BeforeUpload: function (up) {
if (checkReq) {
uploader.stop();
uploader.splice(0, uploader.files.length);
return false;
}
return true;
}
},
init: {
PostInit: function(file) {
...
I had used "dropzone.js" before, and my script worked fine with that but I found that I needed chunked uploads so I had to move to plupload and now my script is being ignored.
Could someone please tell me where I am being stupid here? Thanks!
Got it solved.
It's a nasty, ugly hack, but it works:
Made the "actual" submit/upload button hidden
Made a second button that acts as pre-submit button with onclick function
onclick function calls checkReq and if that returns true, the function calls the click() function of the "actual" submit/upload button
Like I said: nasty but it works.

Angular external templating vs Handlebars external templating

this is how I load and compile my templates in Handlebarsjs,
define([
'jquery',
'handlebars'
],
function ($, Handlebars) {
// #reference: http://berzniz.com/post/24743062344/handling-handlebars-js-like-a-pro
Handlebars.getTemplate = function(name) {
if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) {
$.ajax({
url : 'js/template/' + name + '.handlebars',
success : function(data) {
if (Handlebars.templates === undefined) {
Handlebars.templates = {};
}
Handlebars.templates[name] = Handlebars.compile(data);
},
dataType: "text",
async : false
});
}
return Handlebars.templates[name];
};
// Precompile your templates and add/paste them below here.
});
and I can just retrieve the template with this line below,
this.$el.html(Handlebars.getTemplate('list')({contacts: response}));
So this I don't have to use ajax to call the same template over and over again. I can just get it from the Handlebars' storage.
Is this possible with Angularjs? I have been looking up for tutorials for doing this in Angualrjs but can't find any. Any ideas where is the good start?
Angular.js caches templates when they are requested (so the request only happens once), but you can prepopulate that cache using $templateCache.

Categories