Need if-else advice in actionscript3 - string

function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
message.text = txtMessage.text;
message.userName = txtUser.text;
//Posts to this swf
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function jsalertwindow(event:MouseEvent):void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}
As you can see there are two function which are contain mouseevent. I want to send those function with an if-else statement. If user write something in text input component which name is txtUser and,
send_btn.addEventListener(MouseEvent.CLICK, clickButtonHandler);
will work, else(if the user forget writing anything)
send_btn.addEventListener(MouseEvent.CLICK, jsalertwindow);
will work.
And one more question should i use MouseEvent.CLICK or MouseEvent.MOUSE_DOWN? Thanks for your advice.

Assign a single handler to the button click (MouseEvent.CLICK is the right event to use) and check the field is populated in the handler:
function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
// Check the field is populated
if (txtUser.text != "")
{
message.text = txtMessage.text;
message.userName = txtUser.text;
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
else
{
// Nothing in the input field, show the alert
showAlert();
}
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function showAlert():void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}

Related

Prevent nested lists in text-editor (froala)

I need to prevent/disable nested lists in text editor implemented in Angular. So far i wrote a hack that undos a nested list when created by the user. But if the user creates a normal list and presses the tab-key the list is shown as nested for a few milliseconds until my hack sets in back to a normal list. I need something like event.preventDefault() or stopPropagation() on tab-event keydown but unfortunately that event is not tracked for some reason. Also the froala settings with tabSpaces: falseis not showing any difference when it comes to nested list...in summary i want is: if the user creates a list and presses the tab-key that nothing happens, not even for a millisecond. Has anyone an idea about that?
Froala’s support told us, there’s no built-in way to suppress nested list creation. They result from TAB key getting hit with the caret on a list item. However we found a way to get around this using MutationObserver
Basically we move the now nested list item to his former sibling and remove the newly created list. Finally we take care of the caret position.
var observer = new MutationObserver(mutationObserverCallback);
observer.observe(editorNode, {
childList: true,
subtree: true
});
var mutationObserverCallback = function (mutationList) {
var setCaret = function (ele) {
if (ele.nextSibling) {
ele = ele.nextSibling;
}
var range = document.createRange();
var sel = window.getSelection();
range.setStart(ele, 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
};
var handleAddedListNode = function (listNode) {
if (! listNode.parentNode) {
return;
}
var parentListItem = listNode.parentNode.closest('li');
if (!parentListItem) {
return;
}
var idx = listNode.children.length - 1;
while (idx >= 0) {
var childNode = listNode.children[idx];
if (parentListItem.nextSibling) {
parentListItem.parentNode.insertBefore(childNode, parentListItem.nextSibling);
} else {
parentListItem.parentNode.appendChild(childNode);
}
--idx;
}
setCaret(parentListItem);
listNode.parentNode.removeChild(listNode);
};
mutationList.forEach(function (mutation) {
var addedNodes = mutation.addedNodes;
if (!addedNodes.length) {
return;
}
for (var i = 0; i < addedNodes.length; i++) {
var currentNode = addedNodes[i];
switch (currentNode.nodeName.toLowerCase()) {
case 'ol':
case 'ul':
handleAddedListNode(currentNode);
break;
// more optimizations
}
}
})
};

ReferenceError - Context is not defined (Netsuite)

I am trying to hide a field when a checkbox is checked in an Opportunity but the script I have is throwing a ReferenceError - Context is not defined.
Here is my code:
define(['N/currentRecord','N/search', 'N/format'],
function(currentRecord, search, format) {
function pageInit_disableMyText(scriptContext) {
console.log('START : here you will be able see logs via console (F12 on browser)');
var recCurrent = context.currentRecord; //This represents your current loaded record, you can get the values of the fields here
var myCheckbox = recCurrent.getValue('custbody7'); //This is the code for getting the value of your field
console.log('myCheckbox Value is : ' + myCheckbox);
if(myCheckbox == true)
{
//get the field and disable it
fld1 = recCurrent.getField('custbody3');
fld1.isDisabled = true;
}
else
{
//if you didn't set the field to be disabled by default, then you don't need the code to enable it here
//since it runs only once when the page loads
}
}
function fieldChanged_toggleBox(scriptContext) {
//Different function that triggers on change of a field value, can use this to toggle the checkbox
var currentFieldID = context.fieldId;
console.log('context.fieldId : '+ currentFieldID);
//Check which field is toggled
if(currentFieldID == 'custbody7')
{
//Essentially do the same as above
var recCurrent = context.currentRecord;
var myCheckbox = recCurrent.getValue('custbody7');
if(myCheckbox == true)
{
//get the field and disable it
fld1 = recCurrent.getField('custbody3');
fld1.isDisabled = true;
}
else
{
//Now you need code to enable it as you are toggling the disabling and enabling it realtime
fld1 = recCurrent.getField('custbody3');
fld1.isDisabled = false;
}
}
}
//this is the retrun statement where we declare the script type to implement
return {
pageInit: pageInit_disableMyText,
fieldChanged: fieldChanged_toggleBox
};
});
When I use devtools in Chrome it shows the error on this line:
var recCurrent = context.currentRecord; //This represents your current loaded record, you can get the values of the fields here
But I cannot see what the problem is.
Any help is appreciated.
Thanks!
The parameter name in your function is scriptContext , change it to context
function pageInit_disableMyText(scriptContext) { // <---- Change this parameter to context
Basically you can call it whatever you like, but then you have to use the same variable.

Bot builder : Adaptive cards - call a method when submitting

I need to create a form in which the user has to fill it and to send it. So i have to create a submit button that calls another method but i couldn't find the link between the submit action and the call to another method.
The script of my form is :
public Attachment CreateAdaptiveCardwithEntry()
{
var submitActionData = JObject.Parse("{ \"Type\": \"SaveFunction\" }");
var card = new AdaptiveCard()
{
Body = new List<CardElement>()
{
// Hotels Search form
new TextBlock() { Text = "Titre de la note des frais" },
new TextInput()
{
Id = "titre",
Speak = "<s>Veuillez saisir le titre</s>",
Placeholder = "Veuillez saisir le titre",
Style = TextInputStyle.Text
},
},
Actions = new List<ActionBase>()
{
new SubmitAction()
{
DataJson = submitActionData.ToString()
}
}
};
The script of my card is :
var replyMessage = context.MakeMessage();
replyMessage.Attachments = new List<Attachment> { FraisDialog.CreateAdaptiveCardwithEntry() };
await context.PostAsync(replyMessage, CancellationToken.None);
context.Wait(MessageReceived);
the script in MessageReceivedAsync is :
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
if (message.Value != null)
{
// Got an Action Submit
dynamic value = message.Value;
string submitType = value.Type.ToString();
switch (submitType)
{
case "SaveFunction":
await context.PostAsync("Please complete all the search parameters:\n");
return;
}
}
}
In this example i need to send the information with the Id = "titre" and pprocess it afterwards, i don't know how to send it(DataJson ?) and where(MessageReceivedAsync ?). Can someone help me ? do i need to create another dialog just for the card ?
Ps : all this code is in rootDialog.
i'm not getting the message 'Please complete all the search parameters'
If all of your code is in RootDialog then please use context.Wait(MessageReceivedAsync); after sending your attachment.
i need to send the information with the Id = "titre" and process it afterwards
When clicking the submit button, the form data is send to MessageReceived method as usual. If you want to just access the fields in the adaptive card you can access the dynamic variable value. Here is an example.
var message = await result;
if (message.Value != null)
{
// Got an Action Submit
dynamic value = message.Value;
string submitType = value.Type.ToString();
switch (submitType)
{
case "SaveFunction":
if(value.titre == "")
{
await context.PostAsync("Please complete all the search parameters:\n");
}
else
{
await context.PostAsync($"You entered {value.titre}");
}
return;
}
}

FabricJS double click on objects

I am trying to perform a special action whenever the user double clicks any object located inside the canvas. I have read the docs and not found any mouse:dblclick-like event in the documentation. I tried doing something like:
fabric.util.addListener(fabric.document, 'dblclick', callback);
Which does trigger the dblclick event but does not give specific information about the actual object that is being clicked on the canvas.
Any ideas of the most FabricJS-y way of doing this?
The more elegant way is to override fabric.Canvas._initEventListeners to add the dblclick support
_initEventListeners: function() {
var self = this;
self.callSuper('_initEventListeners');
addListener(self.upperCanvasEl, 'dblclick', self._onDoubleClick);
}
_onDoubleClick: function(e) {
var self = this;
var target = self.findTarget(e);
self.fire('mouse:dblclick', {
target: target,
e: e
});
if (target && !self.isDrawingMode) {
// To unify the behavior, the object's double click event does not fire on drawing mode.
target.fire('object:dblclick', {
e: e
});
}
}
I've also developed a library to implement more events missed in fabricjs : https://github.com/mazong1123/fabric.ext
This is similar to #LeoCreer's answer but actually gets access to the targeted object
fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function (e) {
var target = canvas.findTarget(e);
});
The Correct way to add custom events to Fabric.js
window.fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function (event, self) {
yourFunction(event);
});
or use fabric.ext
I'm using this workaround:
var timer = 0;
canvas.item(0).on('mouseup', function() {
var d = new Date();
timer = d.getTime();
});
canvas.item(0).on('mousedown', function() {
var d = new Date();
if ((d.getTime() - timer) < 300) {
console.log('double click')
}
});
Here is a quick and easy way to add a double click event handler to Fabric JS -
Include following code snippet to your html file. Just ensure this is loaded after the main fabric.js library
<script type="text/javascript">
fabric = (function(f) { var nativeOn = f.on; var dblClickSubscribers = []; var nativeCanvas = f.Canvas; f.Canvas = (function(domId, options) { var canvasDomElement = document.getElementById(domId); var c = new nativeCanvas(domId, options); c.dblclick = function(handler) { dblClickSubscribers.push(handler) }; canvasDomElement.nextSibling.ondblclick = function(ev){ for(var i = 0; i < dblClickSubscribers.length; i++) { console.log(ev); dblClickSubscribers[i]({ e :ev }); } }; return c; }); return f; }(fabric));
</script>
Then add this code to listen a double click event:
canvas.dblclick(function(e) {
});
To get information about the actual object that is being clicked on the canvas, use following method -
canvas.getActiveObject();
eg.
canvas.dblclick(function(e) {
activeObject = canvas.getActiveObject();
});
I am late but now fabricjs has mousedblclick event.
Listed at: http://fabricjs.com/docs/fabric.Object.html
See all events:
http://fabricjs.com/events

How to save base64 file to the client using JavaScript?

I have the gotten a certain result from the Notes tab.
The link you see inside the iframe is the name of the file.
I have the DocumentBody from the annotation in some format that looks like base64.
How do I download it?
Thanks,
Fabio
Perform a JQuery request to a URL like this
Xrm.Page.context.getServerUrl() + "XRMServices/2011/OrganizationData.svc/ActivityMimeAttachmentSet(guid'abc...')?$select=Body"
By specifying the select you will request only what you want.
Assign the result to a variable and prepend
data:application/pdf;base64,
From there you could display it inline as an HTML object or try to open it as a new window with
window.location or window.open or document.location.href
I had already the base64 documentbody string extracted like this:
function getSla() {
// Define SOAP message
var objectId;
if (typeof crmForm === "undefined") {
objectId = parent.crmForm.ObjectId;
}
else {
objectId = crmForm.ObjectId;
}
var xml =
[
"<?xml version='1.0' encoding='utf-8'?>",
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ",
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ",
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">",
GenerateAuthenticationHeader(),
"<soap:Body>",
"<RetrieveMultiple xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>",
"<query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' ",
"xsi:type='q1:QueryExpression'>",
"<q1:EntityName>annotation</q1:EntityName>",
"<q1:ColumnSet xsi:type='q1:AllColumns' />",
"<q1:Distinct>false</q1:Distinct><q1:Criteria><q1:FilterOperator>And</q1:FilterOperator>",
"<q1:Conditions><q1:Condition><q1:AttributeName>objectid</q1:AttributeName><q1:Operator>Equal</q1:Operator>",
"<q1:Values><q1:Value xsi:type=\"xsd:string\">",
objectId,
"</q1:Value></q1:Values></q1:Condition></q1:Conditions></q1:Criteria>",
"</query>",
"</RetrieveMultiple>",
"</soap:Body>",
"</soap:Envelope>"
].join("");
var resultXml = executeSoapRequest("RetrieveMultiple", xml);
var result = filter(resultXml.getElementsByTagName("q1:filename"), function (element) {
return /master.*sla/i.test(element.text);
});
if (result.length == 0) {
return null;
}
else {
return result[0].parentNode;
}
}
function getSlaDocumentBody(sla) {
return sla.getElementsByTagName("q1:documentbody")[0].text;
}
window.open("data:application/pdf;base64," + getSlaDocumentBody(sla));
It opened a new window with the string data:application/pdf.......... in the address bar but did nothing. I would prefer that solution indeed.
Ended up using srasmussen solution in here: http://social.microsoft.com/Forums/en/crm/thread/05134277-dd76-4fbb-8f6e-89b1a2a45af1.
var URL = serverUrl + "/userdefined/edit.aspx?etc=5&id=" + slaId;
$.get(URL, function (data) {
var WRPCTokenElement = $(data).find("[WRPCTokenUrl]");
if (WRPCTokenElement) {
var WRPCTokenUrl = WRPCTokenElement.attr("WRPCTokenUrl");
if (WRPCTokenUrl) {
URL = "/Activities/Attachment/download.aspx?AttachmentType=5&AttachmentId=" + slaId + "&IsNotesTabAttachment=undefined" + WRPCTokenUrl;
window.open(URL);
}
}
return false;
});

Resources