can not load javascript drow2d canvas with manuall extends cods - javascript

I have added some functionality to my objects in draw2d canvas. such as :
var MyConnection= draw2d.Connection.extend({
init:function(attr){
this._super(attr);
this.setRouter(new draw2d.layout.connection.VertexRouter());
this.setOutlineStroke(1);
this.setOutlineColor("#000000");
this.setStroke(3);
this.setColor('#ffffff');
this.setRadius(150);
this.conectionResult={"src":{"nms":true,"trg":true},"trg":{"nms":true,"src":"true"}};
},
onContextMenu:function(x,y){
$.contextMenu({
selector: 'body',
events:{
hide:function(){ $.contextMenu( 'destroy' ); }
},
callback: $.proxy(function(key, options){
switch(key){
case "check":
result = this.checkConection();
this.conectionResult=result;
console.log(result);
if(result.src.trg && result.trg.src){
this.setColor("#FFFFFF");
}else{
this.setColor("#FF4422");
}
break;
case "report":
message=[];
result=this.conectionResult;
if(result.src.trg && result.trg.src){
alert("OK");
}else{
src=this.getSource();
trg=this.getTarget();
if(result.src.nms){
message.push("NMS Can See "+src.userData.dev_name);
if(result.src.trg){
message.push(src.userData.dev_name +" Can See "+trg.userData.dev_name);
}else{
message.push(src.userData.dev_name +" CAN NOT See "+trg.userData.dev_name);
}
}else{
message.push("NMS CAN NOT See "+trg.userData.dev_name);
if(result.src.trg){
message.push(src.userData.dev_name +"Can See "+trg.userData.dev_name);
}else{
message.push(src.userData.dev_name +"CAN NOT See "+trg.userData.dev_name+" Or NMS Can not confirm it");
}
}
if(result.trg.nms){
message.push("NMS Can See "+trg.userData.dev_name);
if(result.trg.src){
message.push(trg.userData.dev_name +" Can See "+src.usedData.dev_name);
}else{
message.push(trg.userData.dev_name +" CAN NOT See "+src.userData.dev_name);
}
}else{
message.push("NMS CAN NOT See "+trg.dev_name);
if(result.src.trg){
message.push(src.userData.dev_name +" Can See "+trg.userData.dev_name);
}else{
message.push(src.userData.dev_name +" CAN NOT See "+trg.userData.dev_name+" Or NMS Can not confirm it.");
}
}
alert(message.join("\n"));
}
break;
case "delete":
var cmd = new draw2d.command.CommandDelete(this);
this.getCanvas().getCommandStack().execute(cmd);
default:
break;
}
},this),
x:x,
y:y,
items:
{
"check":{name:"Check", icon:"edit"},
"report":{name:"Report",icon:"edit"},
"sep1": "---------"
,"delete": {name: "Delete", icon: "delete"}
}
});
},
checkConection:function(){
src=this.getSource();
trg=this.getTarget();
console.log("Source IP:"+src.userData.ip+", Target Ip:"+trg.userData.ip);
results={"src":{"nms":false,"trg":false},"trg":{"nms":false,"src":false}};
$.ajax({
url:"***/index.php?r=/******/check-conection&src="+src.userData.ip+"&trg="+trg.userData.ip,
async:false,
success: function(result){
results=result;
}
});
console.log(results);
this.conectionResult=results;
this.setConectionColor();
return results;
},
setConectionColor:function(){
result=this.conectionResult;
console.log(result);
if(result.src.trg && result.trg.src){
this.setColor("#FFFFFF");
}else{
this.setColor("#FF4422");
}
}
});
~
i used below method to save them via AJAX request in server.
function saveTopology(){
var writer = new draw2d.io.json.Writer();
writer.marshal(canvas, function(json){
var jsonTxt = JSON.stringify(json,null,2); .
$("pre").text(jsonTxt);
});
alert($("pre").text());
draw2d=JSON.stringify(JSON.parse($("pre").html()));
var data={
id :1,
draw2d : draw2d,
map_id : 1
};
var url = "topology/save";
result = AjaxResponce(url,data,"POST");
$("pre").html(result);
displayJSON(canvas);
}
and used below to reload it for next times.
function setTopology(){
write2status("Requesting Topology of map_id 1 ...");
draw2d.Configuration.factory.createConnection = function (sourcePort, targetPort) {
var conn = new MyConnection({});
return conn;
};
var topology = AjaxResponce("topology/get-topology",{tplg_id:tplg_id});
console.log(topology);
data = topology;
var bg_map = "url('"+data.bg_map+"')";
var width = data.width;
var height = data.height;
var background_size = height+"px "+width+"px ";
if(typeof(data.draw2d)==="Array"){
$.each(data.draw2d,function(index,item){
if(typeof(item.userData) != "undefined" &&Object.keys(item.userData).length >0){
if(typeof(item.userData.dev_id) !== "undefined")
usedDevices.push(item.userData.dev_id);
}
});
}
topology=JSON.stringify(data.draw2d);
$(".ui-droppable").css({"background-image":bg_map});
$(".ui-droppable").css({"height":parseInt(height)*1.1});
$(".ui-droppable").css({"width":parseInt(width)*1.1});
write2status("Adding map to page...");
$("pre#json").html(topology);
write2status("Map added...");
}
I set
draw2d.Configuration.factory.createConnection = function (sourcePort, targetPort) {
var conn = new MyConnection({});
return conn;
};`
The functionalities works when i open a new form but nor added functionalities loads after reloading the page while they are asigned to any new objects that add to page after reload.
Can any one help me to solve this problem?

I've solve the problem but not sure is a correct way.
I just changed
var MyConnection= draw2d.Connection.extend({
in first code to
draw2d.Connection = draw2d.Connection.extend({
then removed related codes of 3th file. in this case Draw2d loads My connection instead of default function.

Related

JS page redirect not firing

i having issues getting a page to redirect after a button click and some validation. i have tried multiple soluitons and keep getting to the same result where the address bar populates the url but no redirection. if i refresh with f5 or click on the refresh button of the browser than it works and the page redirects and load fine. this is on all browsers that i have tried. So i must be missing something or doing something wrong. below is my code:
........
..............
//render function for json + templates like handlebars, xml + xslt etc.
render: function (dataItem, statuses) {
$list.html(template(dataItem.content));
// action button events
//$('.action a').on("click",function (e){
$('.action a').bind('click', function(e){
var $this = $(this),
action = $this.attr("action"),
$id = $this.closest('ul').attr('id');
// get which link was click for appropriate action
switch(action){
case 'prev' :
break;;
case 'edit' :
if($this.hasClass("actionEnabled")) {
$().ajaxCall(checkURL,{'ID':$id})
.done(function(data){
if(data.result == 0) {
var baseURL = window.location.href.replace(window.location.hash, '') + '#',
url = baseURL + secondUrl_part + "?ID=" + $id;
// url = "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh"
// tried with javascript all these different methods -> still did not work
// method 1
$(location).attr('href', "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh");
// method 2
window.location = "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh";
// method 3
window.location.href = "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh";
// method 4
window.location.replace("http://mysite/index.php#/page/destPage.php?ID=idabcdefgh");
// even tried with return false as suggested by some people
//return false;
} else {
// todo error message no longer exist
}
})
.fail(function(){
// todo error : could not be loaded
})
} else {
e.preventDefault();
// to do add message cannot edit
}
break;;
case 'del' :
break;
}
});
}
..........
.......
.....
here is the code based on Ivan's answer
//render function for json + templates like handlebars, xml + xslt etc.
render: function (dataItem, statuses) {
$list.html(template(dataItem.content));
// action button events
//$('.action a').on("click",function (e){
$('.action a').bind('click', function(e){
var $this = $(this),
action = $this.attr("action"),
$id = $this.closest('ul').attr('id');
// get which link was click for appropriate action
switch(action){
case 'prev' :
break;;
case 'edit' :
if($this.hasClass("actionEnabled")) {
$().ajaxCall(checkURL,{'ID':$id})
.done(function(data){
if(data.result == 0) {
var baseURL = window.location.href.replace(window.location.hash, '') + '#',
url = baseURL + secondUrl_part + "?ID=" + $id;
$(location).attr('href', url);
location.reload();
} else {
// todo error message no longer exist
}
})
.fail(function(){
// todo error : could not be loaded
})
} else {
e.preventDefault();
// to do add message cannot edit
}
break;;
case 'del' :
break;
}
});
}

How to return false from a main function after an ajax callback?

I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.

How to get system properties __CreatedAt, __Version in javascript backend of Azure Mobile services?

I am trying to explicitly get the system properties from my table but it is not working. I can see that the URL is returning all the data including these fields if I use https://myservice.azure-mobile.net/tables/todoitem?__systemProperties=* but on the code I cannot get it as item.__version or item.version. I have tried adding todoitemtable = WindowsAzure.MobileServiceTable.SystemProperties.All; but no success! I have also looked at http://azure.microsoft.com/en-us/documentation/articles/mobile-services-html-validate-modify-data-server-scripts/ but this is adding a new column instead of using the existing system columns.
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://ib-svc-01.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// = WindowsAzure.MobileServiceTable.SystemProperties.All;
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.id))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
I was trying to access the system properties from within the API scripts and found this and thought it was useful and relevant: http://www.brandonmartinez.com/2014/10/22/retrieve-system-properties-in-azure-mobile-services-javascript-backend/
Basically you can do this (example from the post):
myTable.read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function(tableEntries) {
// So on and so forth
}
}

how to get data from javascript ajax from another page

I am using a script with jQuery:
$(document).ready(function () {
var button;
var line;
var inputs;
var params = {};
var updatefield;
$('button.update').click(function () {
button = $(this);
params['button'] = button.val();
line = button.closest('.line');
updatefield = line.find('td.resultFromGet');
inputs = line.find('input');
inputs.each(function (id, item) {
switch($(item).attr('type')){
case 'checkbox':{
params[$(item).attr('name')] = new Array($(item).is(':checked'));
break;
}
default:{
params[$(item).attr('name')] = new Array($(item).attr('value'));
break;
}
}
});
//alert(JSON.stringify(params, null, 4));
$.get( 'core/ajax/correct_exec.php', params )
.done(function (data){
if(data == '1'){
$(updatefield).html('UPDATE_RECORD_SUCCESS');
} else {
$(updatefield).html( data );
}
});
});
});
The page I am getting is doing echo '1'; from PHP in case of success.
I try to test this with data == 1 but it doesn't work even though it is a success. In fact, it sends me $(updatefield).html( data ); which is 1. So why can't it just print UPDATE_RECORD_SUCCESS?
The data response is coming with white space, if you use trim() function something like this, then if condition should be executed.
if(data.trim() == '1'){
$('#updatefield').html('UPDATE_RECORD_SUCCESS'); //this should be executed
} else {
$('#updatefield').html( data );
}
Here you can see the space with data in chrome debugger.

jQuery Cordova issue- Typerror, undefined is not a function

var dbShell;
function doLog(s){
/*
setTimeout(function(){
console.log(s);
}, 3000);
*/
}
function dbErrorHandler(err){
alert("DB Error: "+err.message + "\nCode="+err.code);
}
function phoneReady(){
doLog("phoneReady");
//First, open our db
dbShell = window.openDatabase("SimpleNotes", 2, "SimpleNotes", 1000000);
doLog("db was opened");
//run transaction to create initial tables
dbShell.transaction(setupTable,dbErrorHandler,getEntries);
doLog("ran setup");
}
//I just create our initial table - all one of em
function setupTable(tx){
doLog("before execute sql...");
tx.executeSql("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY,title,body,updated)");
doLog("after execute sql...");
}
//I handle getting entries from the db
function getEntries() {
//doLog("get entries");
dbShell.transaction(function(tx) {
tx.executeSql("select id, title, body, updated from notes order by updated desc",[],renderEntries,dbErrorHandler);
}, dbErrorHandler);
}
function renderEntries(tx,results){
doLog("render entries");
if (results.rows.length == 0) {
$("#mainContent").html("<p>You currently do not have any notes.</p>");
} else {
var s = "";
for(var i=0; i<results.rows.length; i++) {
s += "<li><a href='edit.html?id="+results.rows.item(i).id + "'>" + results.rows.item(i).title + "</a></li>";
}
$("#noteTitleList").html(s);
$("#noteTitleList").listview("refresh");
}
}
function saveNote(note, cb) {
//Sometimes you may want to jot down something quickly....
if(note.title == "") note.title = "[No Title]";
dbShell.transaction(function(tx) {
if(note.id == "") tx.executeSql("insert into notes(title,body,updated) values(?,?,?)",[note.title,note.body, new Date()]);
else tx.executeSql("update notes set title=?, body=?, updated=? where id=?",[note.title,note.body, new Date(), note.id]);
}, dbErrorHandler,cb);
}
function init(){
document.addEventListener("deviceready", phoneReady, false);
//handle form submission of a new/old note
$("#editNoteForm").live("submit",function(e) {
var data = {title:$("#noteTitle").val(),
body:$("#noteBody").val(),
id:$("#noteId").val()
};
saveNote(data,function() {
$.mobile.changePage("index.html",{reverse:true});
});
e.preventDefault();
});
//will run after initial show - handles regetting the list
$("#homePage").live("pageshow", function() {
getEntries();
});
//edit page logic needs to know to get old record (possible)
$("#editPage").live("pageshow", function() {
var loc = $(this).data("url");
if(loc.indexOf("?") >= 0) {
var qs = loc.substr(loc.indexOf("?")+1,loc.length);
var noteId = qs.split("=")[1];
//load the values
$("#editFormSubmitButton").attr("disabled","disabled");
dbShell.transaction(
function(tx) {
tx.executeSql("select id,title,body from notes where id=?",[noteId],function(tx,results) {
$("#noteId").val(results.rows.item(0).id);
$("#noteTitle").val(results.rows.item(0).title);
$("#noteBody").val(results.rows.item(0).body);
$("#editFormSubmitButton").removeAttr("disabled");
});
}, dbErrorHandler);
} else {
$("#editFormSubmitButton").removeAttr("disabled");
}
});
}
Dats my code, awfully long, huh?
Well anyways I got most of it from here, however I get an error on line 67 saying "TypeError: 'undefined' is not a function.".
I'm using Steroids (phonegap-like) and testing dis on an iPhone simulator. I'm sure it uses some cordova for the database work.
Thank you for your help :-)
Which jQuery version do you use? Because .live() was removed with jQuery 1.9 (http://api.jquery.com/live/). You should use .on() instead: http://api.jquery.com/on/

Categories

Resources