I am using HTML5's FileSystem API With Worklight to create cache files JSON format , I created to file without any problem , the problem is when I try to add some text to the created file , I used fileWriter but it doesn't write any thing .
this is the update function that I developed :
function update(fileName){
function onInitFs(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry .
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.PERSISTENT, 1024*1024, onInitFs, errorHandler);
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
document.querySelector('#example-list-fs-ul').innerHTML = 'Error: ' + msg;
}
}
This is the read function to show the content of the file and it return a blank String :
function read(fileName){
function onInitFs(fs) {
fs.root.getFile(fileName, {}, function(fileEntry) {
// Get a File object representing the file,
// then use FileReader to read its contents.
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
alert(this.result);
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.PERSISTENT, 1024*1024, onInitFs, errorHandler);
}
Any one have any Idea how to fix this and how to successfully write and read from the file ?
Thank You
I think it would be better to use some of the Worklight features designed specifically for the purpose you are trying to achieve, like:
Encrypted cache
JSONStore
Here is a sample that allows to create/edit/read/delete a simple text file.
Hope this helps.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>CordovaApp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!--
<link rel="shortcut icon" href="images/favicon.png">
<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
-->
<link rel="stylesheet" href="css/main.css">
<script>window.$ = window.jQuery = WLJQ;</script>
<script type="text/javascript" charset="utf-8">
/**
* Function called when page has finished loading.
*/
function init(){
console.log("onDeviceReady");
}
onWLReady = function() {
// Wait for PhoneGap to load
document.addEventListener("deviceready", init, false);
}
function createFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false},
function(fileEntry) {
fileEntry.createWriter(
function(writer) {
writer.onwriteend = function(evt) {
log("File created...");
};
writer.onwritestart = function(evt){
log("onwritestart");
};
writer.onwrite = function(evt){
log("onwrite");
};
writer.onerror = function(evt){
log("onerror");
};
writer.write("File created at: " + new Date().toLocaleString());
},
fail);
}
, fail);
},
fail);
}
function editFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: false, exclusive: false},
function(fileEntry) {
fileEntry.createWriter(
function(writer) {
writer.onwriteend = function(evt) {
log("File edited");
};
writer.onwritestart = function(evt){
log("onwritestart");
};
writer.onwrite = function(evt){
log("onwrite");
};
writer.onerror = function(evt){
log("onerror");
};
writer.seek(writer.length);
writer.write("<br>File edited at: " + new Date().toLocaleString());
},
fail);
}
, fail);
},
fail);
}
function readFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {
create : false
},
function(fileEntry){
fileEntry.file(function(file) {
readDataUrl(file);
readAsText(file);
},
fail);
},
fail);
}, fail);
}
function readDataUrl(file){
var reader = new FileReader();
log("readDataUrl...");
reader.onloadstart = function(evt){
log("onloadstart: " + evt.target.result);
};
reader.onload = function(evt){
log("onload: " + evt.target.result);
};
reader.onloadend = function(evt){
log("onloadend: " + evt.target.result);
};
reader.onerror = function(evt){
log("onerror: " + evt.target.result);
};
reader.readAsDataURL(file);
reader.abort();
}
function readAsText(file){
var reader = new FileReader();
log("readAsText...");
reader.onloadstart = function(evt){
log("onloadstart: " + evt.target.result);
};
reader.onload = function(evt){
log("onload: " + evt.target.result);
};
reader.onloadend = function(evt){
log("onloadend: " + evt.target.result);
};
reader.onerror = function(evt){
log("onerror: " + evt.target.result);
};
reader.readAsText(file);
}
function deleteFile() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function(fileSystem) {
fileSystem.root.getFile("readme.txt", {
create : false
},
function(fileEntry){
fileEntry.remove(function() {log("File deleted.");
},
fail);
},
fail);
}, fail);
}
function fail(error){
var msg = error;
switch(error.code)
{
case FileError.NOT_FOUND_ERR:
msg = "File Not Found";
break;
case FileError.SECURITY_ERR:
msg = "Security Error";
break;
case FileError.ABORT_ERR:
msg = "Abort error";
break;
case FileError.NOT_READABLE_ERR:
msg = "Not Readable";
break;
case FileError.ENCODING_ERR:
msg = "Encoding Error";
break;
case FileError.NO_MODIFICATION_ALLOWED_ERR:
msg = "No Modification Allowed";
break;
case FileError.INVALID_STATE_ERR:
msg = "Invalid State";
break;
case FileError.SYNTAX_ERR:
msg = "Syntax Error";
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = "Invalid Modification Error";
break;
case FileError.QUOTA_EXCEEDED_ERR:
msg = "Quota Exceeded";
break;
case FileError.TYPE_MISMATCH_ERR:
msg = "Type Mismatch Error";
break;
case FileError.PATH_EXISTS_ERR:
msg = "Path Already Exists Error";
break;
}
log("fail: "+ msg);
}
function log(info){
document.getElementById('log').innerHTML += "<br>" + info;
}
function clearLog(info){
document.getElementById('log').innerHTML = "";
}
</script>
</head>
<body style="display: none;">
<!--application UI goes here-->
<div>
<button onclick="createFile();">Create File</button><br>
<button onclick="editFile();">Edit File</button><br>
<button onclick="readFile();">Read File</button><br>
<button onclick="deleteFile();">Delete File</button><br>
<button onclick="clearLog();">Clear Log</button><br>
</div>
<script src="js/initOptions.js"></script>
<script src="js/main.js"></script>
<script src="js/messages.js"></script>
<div><u><b>Log:</b></u></div>
<div id=log></div>
</body>
</html>
Note that the Javascript methods should better be in js/main.js instead of being defined in the html file. It was simply easier for me to provide a working sample as a single file.
Related
I'm using sockjs-0.3.4.
Before change page structure, it worked normally.
However after changing some stuff. abrubtly ws.onmessage function is beginning not to called.
I checked the connection with server by looking into devtools.
It looks like getting data from the server.
Please help me to know what's the point to check out.
enter image description here
var statusWatcher = {
curPage:"",
ws: null,
wsBaseUrl :null,
uid: null,
init : function(url ){
if(statusWatcher.ws != null) return;
console.log(statusWatcher.ws);
console.log("wsBaseUrl:"+url)
statusWatcher.wsBaseUrl = url;
var browserSupport = ("WebSocket" in window)? true: false;
if(browserSupport){
statusWatcher.start();
}else{
console.log("WebSocket is Not supported by your Web Browser!");
}
//log.eventHandler(1);
},
start : function(){
baseWsURL = statusWatcher.wsBaseUrl+"/statusCheck?&uid="+statusWatcher.uid;
console.log("web socket baseurl:"+baseWsURL);
try{
statusWatcher.ws = new WebSocket(baseWsURL);
} catch (e){
console.log(e);
}
statusWatcher.ws.onopen = function() {
console.log("web socket Opened! ");
};
statusWatcher.ws.onclose = function() {
console.log("web syslog socket Closed! ");
};
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
statusWatcher.ws.onmessage = function(evt) {
console.log("get message...");
//console.log("page:"+curPage);
var data = evt.data;
console.log(data);
var msg;
if(curPage =="main") return;
var e = JSON.parse(data);
if(e.status =="COMPLETE"){
$("#" + e.groupId).text("complete");
$("#" + e.groupId).removeClass('run error');
$("#" + e.groupId).addClass('complete');
statusWatcher.updateScoreState(e.groupId, "COMPLETE", e.topRplRate,e.topKwdRate);
}else if(e.status == "ERROR"){
$("#" + e.groupId).text("error");
$("#" + e.groupId).removeClass('run complete');
$("#" + e.groupId).addClass('error');
statusWatcher.updateScoreState(e.groupId, "ERROR");
}else{
$("#" + e.groupId).html("running("+e.progress+"/"+e.total+")");
$("#" + e.groupId).removeClass('error complete');
$("#" + e.groupId).addClass('run');
statusWatcher.updateScoreState(e.groupId, "RUNNING");
}
};
},
}
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<script src="<c:url value="js/fileuploadMain/statusWatcher.js"/>"></script>
</head>
<body>
<!--header-->
<c:import url="/WEB-INF/jsp/fileupload/header.jsp" />
<!--contents-->
<div class="contents">
<div class="container" id="container">
</div>
</div>
<script>
$(document).ready(function() {
var nice = $("html").niceScroll(); // The document page (body)
$(".select-items").niceScroll({
zindex: "auto",boxzoom:false
});
$("#container").load("group.do");
calaendar.init();
var wsBaseUrl = "ws://"+document.location.host+"<c:out value="${pageContext.request.contextPath}"/>";
statusWatcher.init(wsBaseUrl);
});
</script>
</body>
</html>
statusWatcher.ws = function(err) {
console.log("web syslog socket Error: " + err);
};
I changed upper source code to the next.. Maybe I remove the function name mistakenly..
statusWatcher.ws.onerror = function(err) {
console.log("web syslog socket Error: " + err);
};
How read and write html or php file using ace editor ( alloyoui ), in the example i just get value to edit not from file and i have done to see the documentation but not get how read and write code from file.
example
YUI().use(
'aui-ace-editor',
function(Y) {
var editor = new Y.AceEditor(
{
boundingBox: '#myEditor',
height: '200',
mode: 'javascript',
value: 'alert("Write something here...");',
width: '700'
}
).render();
var mode = Y.one('#mode');
if (mode) {
var contents = {
javascript: 'alert("Write something here...");',
json: '{"value": "Write something here..."}',
php: '<?php echo "Write something here..."; ?>',
xml: '<value attr="something">Write something here...</value>'
};
var currentMode = 'javascript';
var updateValue = function() {
editor.set('value', contents[currentMode]);
};
mode.on(
'change',
function(event) {
currentMode = this.val();
editor.set('mode', currentMode);
updateValue();
}
);
}
}
);
how call the file code? or this can be done only change the value: 'alert("Write something here...");'whit file path/url?
thanks
You cannot write to or read system files with JavaScript. However, you can kind of write to files by reading the contents of uploaded files and loading them into the AceEditor. Use an <input type="file" /> to allow the user to upload the file. Once the file is uploaded, set the AceEditor's value to be the file's contents.
AUI().use('aui-ace-editor', function(A) {
var aceEditor;
var fileInput = A.one('#fileInput');
fileInput.on('change', function(event) {
var file = fileInput.getDOMNode().files[0];
if (file) {
// Other types may also be appropriate here:
if (file.type.startsWith('text/') || file.type.startsWith('application/')) {
var reader = new FileReader();
reader.onload = function (onloadEvent) {
if (!aceEditor) {
aceEditor = new A.AceEditor({
/* ...your AceEditor config... */
mode: 'text',
render: true
});
}
aceEditor.set('value', onloadEvent.target.result);
}
reader.onerror = function (onerrorEvent) {
alert('File could not be read. Aborting.')
}
reader.readAsText(file, "UTF-8");
}
else {
alert('File does not contain text. Aborting.');
}
}
});
});
You can also attempt to guess the mode that the editor should use from the file's mime type:
aceEditor.set('mode', file.type.replace(/^(text|application)\/(x-)?/, ''));
To download the edited file, you can use a data URI:
var downloadFileButton = Y.one('#downloadFileButton');
downloadFileButton.on('click', function(clickEvent) {
var downloadFileLink = Y.Node.create('<a href="data:' +
fileType + ';charset=utf-8,' +
encodeURIComponent(aceEditor.get('value')) +
'" download="' + fileName + '" style="display: none;" />');
var bodyElement = Y.one('body');
bodyElement.appendChild(downloadFileLink);
downloadFileLink.getDOMNode().click();
bodyElement.removeChild(downloadFileLink);
});
Here's a runnable example with all of the above features/code:
YUI().use('aui-ace-editor', function(Y) {
var aceEditor;
var fileName;
var fileType;
var fileInput = Y.one('#fileInput');
fileInput.on('change', function(event) {
var file = fileInput.getDOMNode().files[0];
if (file) {
fileType = file.type;
// Other types may also be appropriate here:
if (fileType.startsWith('text/') || fileType.startsWith('application/')) {
fileName = file.name;
var reader = new FileReader();
reader.onload = function (onloadEvent) {
if (!aceEditor) {
aceEditor = new Y.AceEditor({
boundingBox: '#aceEditor',
mode: 'text',
value: 'Upload a file to begin editing.',
height: '200',
width: '700',
render: true
});
var downloadFileButton = Y.one('#downloadFileButton');
downloadFileButton.setStyle('display', null);
downloadFileButton.on('click', function(clickEvent) {
var downloadFileLink = Y.Node.create('<a href="data:' +
fileType + ';charset=utf-8,' +
encodeURIComponent(aceEditor.get('value')) +
'" download="' + fileName + '" style="display: none;" />');
var bodyElement = Y.one('body');
bodyElement.appendChild(downloadFileLink);
downloadFileLink.getDOMNode().click();
bodyElement.removeChild(downloadFileLink);
});
}
aceEditor.set('value', onloadEvent.target.result);
aceEditor.set('mode', fileType.replace(/^(text|application)\/(x-)?/, ''));
}
reader.onerror = function (onerrorEvent) {
alert('File could not be read. Aborting.')
}
reader.readAsText(file, "UTF-8");
}
else {
alert('File does not contain text. Aborting.');
}
}
});
});
<script src="https://cdn.rawgit.com/stiemannkj1/701826667a70997013605edcd37e92a6/raw/469fe1ae297e72a5a80eb9015003b7b04eac735e/alloy-ui-3.0.1_aui_aui-min.js"></script>
<link href="https://cdn.rawgit.com/stiemannkj1/90be22de7f48c729b443af14796d91d3/raw/a9f35ceedfac7fc0559b121bed105eaf80f10bf2/aui-css_css_bootstrap.min.css" rel="stylesheet"></link>
<div class="yui3-skin-sam">
<input type="file" id="fileInput">
<div id="aceEditor"></div>
<button id="downloadFileButton" style="display: none;">Download File</button>
</div>
I have a View in which i have criteria a Supplier TextBox a LastMonth dropdown and a Months Textbox.
#using JouleBrokerDB.ViewModels;
#model AssignPayReportToDepositViewModel
#{
ViewBag.Title = "View";
}
<link href="#Url.Content("~/Content/kendo/kendo.common-bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.dataviz.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/kendo/kendo.dataviz.bootstrap.min.css")" rel="stylesheet" />
<style>
.treediv {
display: inline-block;
vertical-align: top;
width: 440px;
/*height:400px;*/
min-height: 400px;
text-align: left;
margin: 0 2em;
border-radius: 25px;
border: 2px solid #8AC007;
padding: 15px;
overflow: auto;
}
</style>
<div class="row">
<div class="col-md-9 col-md-offset-1">
#using (Html.BeginForm("Show", "AssignPayReportToDeposit", FormMethod.Post, new { id = "AssignToPayReportForm", #class = "form-horizontal" }))
{
<fieldset>
<!-- Form Name -->
<legend>Assign Pay Report to Deposit</legend>
<div class="form-group">
<!-- Supplier -->
<div class="col-sm-4">
#Html.Label("", "Supplier:", new { #class = "control-label", #for = "textinput" })
<div id="suppliers">
#Html.DropDownListFor(x => x.SuppliersList, new SelectList(Model.SuppliersList, "SupplierID", "Name"), new { id = "ddSupplier", #class = "form-control" })
</div>
</div>
<!-- Last Month -->
<div class="col-sm-4">
#Html.Label("", "Last Month:", new { #class = "control-label", #for = "textinput" })
#Html.DropDownListFor(x => x.LastMonthsList, new SelectList(Model.LastMonthsList), new { #id = "ddLastMonth", #class = "form-control" })
</div>
<!-- Months-->
<div class="col-sm-4">
#Html.Label("", "Months:", new { #class = "control-label", #for = "textinput" })
#Html.TextBox("txtMonths", null, new { type = "number", step = 1, min = 1, max = 12, #class = "form-control", required = "required" })
</div>
</div>
</fieldset>
<div class="treediv">
#Html.Label("", "UnAssigned PayReport:", new { #class = "control-label", #for = "textinput" })
<div id="TreeView_UPR" style="padding:5px"></div>
</div>
<div class="treediv">
#Html.Label("", "Deposits:", new { #class = "control-label", #for = "textinput" })
<h4></h4>
<div id="TreeView_AD" style="padding:5px"></div>
</div>
}
</div>
</div>
<script src="#Url.Content("~/Scripts/kendo/kendo.all.min.js")"></script>
<script src="#Url.Content("~/Scripts/Views/AssignPayReportToDeposit/Show.js")"></script>
Here on this text box i have attached changed event though jQuery. The requirement is that whenever the criteria changes the treeview div will be filled with data will be refreshed.
AssignPayReportsToDeposit.AttachEvents = function () {
$("#ddSupplier").change(AssignPayReportsToDeposit.OnSupplierChange);
$("#ddLastMonth").change(AssignPayReportsToDeposit.OnLastMonthChange);
$("#txtMonths").change(AssignPayReportsToDeposit.OnMonthsChange);
}
these changed event handler will handle the refreshing the treeview. The whole thing is handled through ajax calls.
Now i know that using Ajax.ActionLink and UpdateTargetId parameter with Replace option i can return the treeview in partial view so the manual handling can be removed. but that will require me put the anchor button which user have to click. Requirement is that the refresh of treeview should be done on any criteria change.
Is there any way i am able to achieve this using Ajax.ActionLink (or any another razor syntax that will take load off from the manual handling ) ? On change event of the controls i would like to call a controller using ajax.actionlink which will return a partialview and update the div.
Edit: I am handling this through jQuery right now. so i will post the complete code for more understanding.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JouleBrokerDB;
using JouleBrokerDB.ViewModels;
using JouleBroker.Filters;
namespace JouleBroker.Controllers
{
[RoutePrefix("AssignPayReportToDeposit")]
[Route("{action=Show}")]
public class AssignPayReportToDepositController : Controller
{
// GET: AssignPayReportToDeposit
//[Route("Show",Name = "APTDShow")]
//[ValidateLogin]
public ActionResult Show()
{
List<SupplierViewModel> suppliers = DBCommon.GetAllSuppliers(false);
SuppliersList_LastMonthsList_ViewModel model = new SuppliersList_LastMonthsList_ViewModel()
{
SuppliersList = suppliers,
LastMonthsList = new List<string>()
};
return View(model);
}
[HttpPost]
[Route("GetUnAssignedPayReports")]
public JsonResult GetUnAssignedPayReports(int SupplierID,
string MonthPaid,
int Months)
{
var payreports = AssignPayReportsToDepositData.GetUnAssignedPayReports(SupplierID,
MonthPaid,
Months);
return Json(payreports);
}
[HttpPost]
[Route("GetAssignedPayReports")]
public JsonResult GetAssignedPayReports(int SupplierID,
string MonthPaid,
int Months)
{
var payreports = AssignPayReportsToDepositData.GetAssignedPayReports(SupplierID,
MonthPaid,
Months);
return Json(payreports);
}
[HttpPost]
[Route("AssignDepositIdToPayReport")]
public bool AssignDepositIdToPayReport(int PayReportID, int DepositID)
{
return AssignPayReportsToDepositData.AssignDepositIdToPayReport(PayReportID, DepositID);
}
}
}
JavaScript File (the code is a bit lengthy so you don't need to look at all of them you can see the methods which are calling the action methods. GetUnAssignedPayReports and GetAssignedPayReports which returns the data which is used to fill the tree view.) I just want this portion to moved to partial view and passing model to partial view generate treeview there and replace the div each time on change event with rendering partial view again. Hope i am clear enough. so change the above methods to return partial instead of json result that what i am trying to achive
function AssignPayReportsToDeposit() { }
AssignPayReportsToDeposit.SelectedSupplierID = 0;
AssignPayReportsToDeposit.SelectedLastMonth = null;
AssignPayReportsToDeposit.SelectedMonths = 0;
AssignPayReportsToDeposit.LastMonthsList = null;
AssignPayReportsToDeposit.UnAssignedPayReportsList = null;
AssignPayReportsToDeposit.AssignedPayReportsList = null;
AssignPayReportsToDeposit.LastTextChangedNode = null;
//--------- Document Ready Function -------- //
$(document).ready(function () {
//AttachEvents
AssignPayReportsToDeposit.AttachEvents();
});
AssignPayReportsToDeposit.AttachEvents = function () {
$("#ddSupplier").change(AssignPayReportsToDeposit.OnSupplierChange);
$("#ddLastMonth").change(AssignPayReportsToDeposit.OnLastMonthChange);
$("#txtMonths").change(AssignPayReportsToDeposit.OnMonthsChange);
}
//Handles Supplier ChangeEvents
AssignPayReportsToDeposit.OnSupplierChange = function () {
//Get Changed Supplier ID
AssignPayReportsToDeposit.SelectedSupplierID = $('#ddSupplier').val();
//Get Last Month List
AssignPayReportsToDeposit.LastMonthsList = CommonAction.GetLastPayReportMonthsBySupplierID(AssignPayReportsToDeposit.SelectedSupplierID);
//Fill Last Month List
AssignPayReportsToDeposit.FillLastMonths();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Handles Last Month Change Event
AssignPayReportsToDeposit.OnLastMonthChange = function () {
AssignPayReportsToDeposit.SelectedLastMonth = $('#ddLastMonth').val();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Handles Month Change Event
AssignPayReportsToDeposit.OnMonthsChange = function () {
AssignPayReportsToDeposit.SelectedMonths = $('#txtMonths').val();
//Refresh TreeView_UPR
AssignPayReportsToDeposit.RefreshTreeViewUPR();
//Refresh TreeView_AD
AssignPayReportsToDeposit.RefreshTreeViewAD();
}
//Fills Last Month Dropdown with options
AssignPayReportsToDeposit.FillLastMonths = function () {
var ddLastMonth = $("#ddLastMonth");
if (ddLastMonth != undefined) {
ddLastMonth.empty();
if (AssignPayReportsToDeposit.LastMonthsList != undefined) {
$.each(AssignPayReportsToDeposit.LastMonthsList, function () {
Common.AddOptionToSelect(ddLastMonth, this.Text, this.Text);
});
ddLastMonth.val(AssignPayReportsToDeposit.LastMonthsList[0].Text);
AssignPayReportsToDeposit.SelectedLastMonth = ddLastMonth.val();
}
}
}
AssignPayReportsToDeposit.ValidateControls = function () {
var success = true;
if (AssignPayReportsToDeposit.SelectedSupplierID == undefined ||
AssignPayReportsToDeposit.SelectedSupplierID == 0) {
// bootbox.alert('Please select a Supplier');
success = false;
}
else if (AssignPayReportsToDeposit.SelectedLastMonth == undefined ||
AssignPayReportsToDeposit.SelectedLastMonth == '') {
// bootbox.alert('Please select Last Month');
success = false;
}
else if (AssignPayReportsToDeposit.SelectedMonths == undefined ||
AssignPayReportsToDeposit.SelectedMonths == 0) {
// bootbox.alert('Please Enter Months');
success = false;
}
return success;
}
//Assigns DepositIdToPayReport
AssignPayReportsToDeposit.AssignDepositIdToPayReport = function (PayReportID, DepositID) {
var success = false;
if (PayReportID != undefined && DepositID != undefined) {
var jsonData = JSON.stringify({ PayReportID: PayReportID, DepositID: DepositID });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'AssignPayReportToDeposit/AssignDepositIdToPayReport',
data: jsonData,
async: false,
success: function (result) {
success = result;
},
error: Common.AjaxErrorHandler
});
}
return success;
}
//--------- Tree View UPR Functions -------- //
//Gets UnAssigned Pay Reports
AssignPayReportsToDeposit.GetUnAssignedPayReports = function () {
var payReports;
if (AssignPayReportsToDeposit.ValidateControls()) {
var jsonData = JSON.stringify(
{
SupplierID: AssignPayReportsToDeposit.SelectedSupplierID,
MonthPaid: AssignPayReportsToDeposit.SelectedLastMonth,
Months: AssignPayReportsToDeposit.SelectedMonths
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AssignPayReportToDeposit/GetUnAssignedPayReports",
data: jsonData,
async: false,
success: function (data) {
if (data != undefined && data != "")
payReports = data;
},
error: Common.AjaxErrorHandler
});
}
return payReports;
}
AssignPayReportsToDeposit.BindTreeViewUPR = function () {
var treeview = $("#TreeView_UPR");
var inline = new kendo.data.HierarchicalDataSource({
data: AssignPayReportsToDeposit.UnAssignedPayReportsList,
schema: {
model: {
id: "PayReportID"
}
}
});
treeview.kendoTreeView({
dragAndDrop: true,
dataSource: inline,
dataBound: function (e) {
if (!this.dataSource.data().length) {
this.element.append("<p class='no-items'>No items yet.</p>");
} else {
this.element.find(".no-items").remove();
}
},
dataTextField: ["DisplayValue"],
drop: AssignPayReportsToDeposit.OnTreeViewUPRDrop
});
}
AssignPayReportsToDeposit.OnTreeViewUPRDrop = function (e) {
var isTargetTreeViewAD = false;
var sourceDataItem = this.dataItem(e.sourceNode);
var targetDataItem = this.dataItem(e.destinationNode);
if (targetDataItem == undefined) {
targetDataItem = $("#TreeView_AD").data("kendoTreeView").dataItem(e.destinationNode);
isTargetTreeViewAD = true;
}
if (sourceDataItem == undefined ||
targetDataItem == undefined) {
//Source and target both must exists
e.preventDefault();
return;
}
if (sourceDataItem.IsDeposit == true) {
//Deposits cannot be drag and Drop
e.preventDefault();
return;
}
if (isTargetTreeViewAD) {
if (e.dropPosition == "over" &&
sourceDataItem.IsPayReport == true &&
sourceDataItem.IsAssignedPayReport == false &&
targetDataItem.IsDeposit == true) {
//Source must UnAssigned Payreport Target Must be Deposit and Drop position must over
//Implement logic to assign deposit id to the Pay Report
var PayReportID = sourceDataItem.PayReportID;
var DepositID = targetDataItem.DepositID;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", true);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
else {
if ((e.dropPosition == "before" || e.dropPosition == "after") &&
sourceDataItem.IsPayReport == true &&
targetDataItem.IsPayReport == true &&
targetDataItem.IsAssignedPayReport == false) {
//Only allow sorting in this condition otherwise cancel drop event
//Means only allow sorting of unassigned payreports within the tree
}
else {
e.preventDefault();
return;
}
}
}
AssignPayReportsToDeposit.RefreshTreeViewUPR = function () {
//Destroy and empty tree
var treeview = $("#TreeView_UPR").data("kendoTreeView");
if (treeview != undefined) { treeview.destroy(); }
treeview = $("#TreeView_UPR");
treeview.empty();
AssignPayReportsToDeposit.UnAssignedPayReportsList = AssignPayReportsToDeposit.GetUnAssignedPayReports();
AssignPayReportsToDeposit.BindTreeViewUPR();
}
//--------- TreeView_AD Functions -------- //
//Gets Assigned Pay Reports
AssignPayReportsToDeposit.GetAssignedPayReports = function () {
var payReports;
if (AssignPayReportsToDeposit.ValidateControls()) {
var jsonData = JSON.stringify(
{
SupplierID: AssignPayReportsToDeposit.SelectedSupplierID,
MonthPaid: AssignPayReportsToDeposit.SelectedLastMonth,
Months: AssignPayReportsToDeposit.SelectedMonths
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "AssignPayReportToDeposit/GetAssignedPayReports",
data: jsonData,
async: false,
success: function (data) {
if (data != undefined && data != "")
payReports = data;
},
error: Common.AjaxErrorHandler
});
}
return payReports;
}
AssignPayReportsToDeposit.BindTreeViewAD = function () {
var treeview = $("#TreeView_AD");
var inline = new kendo.data.HierarchicalDataSource({
data: AssignPayReportsToDeposit.AssignedPayReportsList,
schema: {
model: {
id: "DepositID",
hasChildren: "HasAnyAssignedPayReports",
children: "AssignedPayReports"
}
}
});
treeview.kendoTreeView({
dragAndDrop: true,
dataSource: inline,
dataBound: function (e) {
if (!this.dataSource.data().length) {
this.element.append("<p class='no-items'>No items yet.</p>");
} else {
this.element.find(".no-items").remove();
}
},
dataTextField: ["DisplayValue", "DisplayValue"],
drop: AssignPayReportsToDeposit.OnTreeViewADDrop,
select: AssignPayReportsToDeposit.OnTreeViewADSelect
});
}
AssignPayReportsToDeposit.OnTreeViewADSelect = function (e) {
var dataItem = this.dataItem(e.node);
var treeview = this;
if (AssignPayReportsToDeposit.LastTextChangedNode != undefined) {
//Restore last node's Text
var previousDataItem = this.dataItem(AssignPayReportsToDeposit.LastTextChangedNode);
if (previousDataItem != undefined) {
var date = AssignPayReportsToDeposit.FormatDepositMonthToDisplay(previousDataItem.DepositDate);
var displaytext = "[" + date + "]" + "-[" + previousDataItem.BankName + "]-" + "[" + previousDataItem.Amount + "]";
this.text(AssignPayReportsToDeposit.LastTextChangedNode, displaytext);
}
AssignPayReportsToDeposit.LastTextChangedNode = undefined;
}
if (dataItem.IsDeposit) {
if (dataItem.hasChildren > 0) {
dataItem.set("expanded", true);
//Append sum to selected node's diplay value
var childs = dataItem.children.data();
var sum = 0;
$.each(childs, function () { sum += this.Amount });
var date = AssignPayReportsToDeposit.FormatDepositMonthToDisplay(dataItem.DepositDate);
var displaytext = "[" + date + "]" + "-[" + dataItem.BankName + "]-" + "[" + dataItem.Amount + "(" + sum + ")" + "]";
this.text(e.node, displaytext)
AssignPayReportsToDeposit.LastTextChangedNode = e.node;
}
}
}
AssignPayReportsToDeposit.FormatDepositMonthToDisplay = function (jsondate) {
var depositedate = "";
if (jsondate != undefined && jsondate != "") {
var date = Common.ParseDate(jsondate);
var month = ("0" + (date.getMonth() + 1)).slice(-2);
depositedate = date.getFullYear() + "-" + (month);
}
return depositedate;
}
AssignPayReportsToDeposit.OnTreeViewADDrop = function (e) {
var isTargetTreeViewURP = false;
var DroptoNoItemZone = false;
var sourceDataItem = this.dataItem(e.sourceNode);
var targetDataItem = this.dataItem(e.destinationNode);
var treeview_UPR = $("#TreeView_UPR").data("kendoTreeView");
if (targetDataItem == undefined) {
targetDataItem = treeview_UPR.dataItem(e.destinationNode);
if (treeview_UPR.element.find(".no-items").length > 0) DroptoNoItemZone = true;
isTargetTreeViewURP = true;
}
if ((sourceDataItem == undefined ||
targetDataItem == undefined) && DroptoNoItemZone == false) {
e.preventDefault();
return;
}
if (sourceDataItem.IsDeposit == true) {
//Deposits can not be moved within the tree view
e.preventDefault();
return;
}
if (isTargetTreeViewURP) {
if (((e.dropPosition == "before" || e.dropPosition == "after") &&
sourceDataItem.IsPayReport == true &&
sourceDataItem.IsAssignedPayReport == true &&
targetDataItem.IsPayReport == true) || (e.dropPosition == "over" && DroptoNoItemZone)) {
//Implement logic to unassing deposit id to PayReport
var PayReportID = sourceDataItem.PayReportID;
var DepositID = 0;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", false);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
else {
if (e.dropPosition == "over" &&
sourceDataItem.IsPayReport == true &&
targetDataItem.IsDeposit == true) {
//Implement Logic to change deposit ID for assigned payreport
var PayReportID = sourceDataItem.PayReportID;
var DepositID = targetDataItem.DepositID;
if (AssignPayReportsToDeposit.AssignDepositIdToPayReport(PayReportID, DepositID)) {
sourceDataItem.set("DepositID", DepositID);
sourceDataItem.set("IsAssignedPayReport", true);
}
else {
//Didnt update the record don't do the drop
e.preventDefault();
return;
}
}
else {
e.preventDefault();
return;
}
}
}
AssignPayReportsToDeposit.RefreshTreeViewAD = function () {
//Destroy and empty tree
var treeview = $("#TreeView_AD").data("kendoTreeView");
if (treeview != undefined) { treeview.destroy(); }
treeview = $("#TreeView_AD");
treeview.empty();
AssignPayReportsToDeposit.LastTextChangedNode = undefined;
AssignPayReportsToDeposit.AssignedPayReportsList = AssignPayReportsToDeposit.GetAssignedPayReports();
AssignPayReportsToDeposit.BindTreeViewAD();
}
Unfortunately not out the box.
The Ajax extension methods are really just HTML helpers that work with other jQuery libraries. The helpers create the relavant HTML markup (such as adding custom addtributes data-*="") and the client scripts use this to determine their behaviour.
You could create your own MVC HTML helper and script library to handle change events for you however I would recommend looking at a front end framework such as Angular instead. This library would handle all the events declaratively so you don't need to waste time writing event handlers.
I am working on jQuery mobile dynamic dialog. Everything is working fine except the close event.
$(document).ready(function () {
$('#btnalert').click(function () {
alert('click');
msg('hello', 'info', function () {
alert('call back function');// this line is not called
});
});
});
function msg(_msg, _title, _okCB) {
try {
if (_title == null || _title == undefined || _title == '') {
_title = 'Information';
}
if (_msg == null || _msg == undefined || _msg == '') {
_msg = 'Error found. Please contact your administrator.';
}
// Create it in memory
var dlg = $("<div id=\"dlgAlert\" class=\"ui-corner-all ui-shadow\" data-close-btn=\"right\" />")
.attr("data-role", "dialog")
.attr("id", "dialog");
var header = $("<div />")
.attr("data-role", "header")
.attr("role", "banner")
.html("<h2>" + _title + "</h2>");
var content = $("<div style=\"padding: 15px;\" />")
.attr("data-role", "content")
.append($("<p />").html(_msg));
content.append("<div ><a class='dlgalert' href='#index' data-rel='back' data-role=\"button\" data-theme=\"c\" >Close</a></div>");
dlg.append(header).trigger('create');
dlg.append(content).trigger('create');
dlg.appendTo($.mobile.pageContainer);
$.mobile.changePage(dlg, {
transition: "pop",
role: "dialog",
reverse: false
});
} catch (e) {
alert(e);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" rel="stylesheet"/>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<a id="btnalert" data-role="button"> alert</a>
add below code in your function . check here DEMO
dialogs are simply pages which display dialogs . so here you can call pagehide event.
dlg.on("pagehide",function(){
alert("Dialog closed");
});
or check DEMO
dlg.off("pagehide").on("pagehide",function(){
alert("Dialog closed");
});
I'm trying to keep subscribed to blockchain.info websocket api for new blocks. I basically took the code off http://www.websocket.org/echo.html and plugged in blockchain.info parameters. It works, but I'm finding that after a while it will automatically disconnect. How do I keep the session alive?
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var wsUri = "wss://ws.blockchain.info/inv";
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("{\"op\":\"blocks_sub\"}");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
//websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
I just tested this, and it seems to work:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready
(
function(){
initWebSocket();
}
);
</script>
<script language="javascript" type="text/javascript">
function initWebSocket()
{
// init blockchain websocket (activity, blocks)
var blockchain = new WebSocket('ws://ws.blockchain.info:8335/inv');
blockchain.onerror = function (error){ console.log('connection.onerror',error); };
blockchain.onopen = function ()
{
blockchain.send( JSON.stringify( {"op":"unconfirmed_sub"} ) ); // subscribe to uncofirmed activity
};
blockchain.onmessage = function (message)
{
var response = JSON.parse(message.data);
var date = new Date(0);
date.setUTCSeconds( response.x.time );
if( response.op == "utx")
{
var amount = 0;
for(var i=0;i<response.x.out.length;i++)
amount += response.x.out[i].value;
// amount is in satoshi
// 1 BTC = 100,000,000 Satoshi (https://en.bitcoin.it/wiki/activity)
response.amount = amount / 100000000;
}
console.log( response.op, response );
};
}
Largely taken from here: http://bl.ocks.org/npedrini/6030317