Click on something that's not a sprite - phaser-framework

I'm tryng to handle a click event that does not clicked on a sprite.
My first aproach would be handling normal JS events:
class EditorListener {
constructor(editor) {
...
if(window) {
window.addEventListener('click', this.onWindowClick.bind(this));
}
}
onWindowClick(event) {
if(event.target && event.target.tagName == 'CANVAS') {
Events.fire(EventType.CLICK_NOWHERE);
}
}
}
...
The problem is that this is called when I click sprites.
The goal is to simply close a dialog when I click nowhere.

Tap anywhere and run the function:
game.input.onTap.add(onTap, this);
function onTap(pointer)
{
}
Tap on these objects and run the function onDown
// enable input for some objects
yourObject1.inputEnabled = true;
yourObject2.inputEnabled = true;
yourObject1.events.onInputDown.add(onDown, this);
yourObject2.events.onInputDown.add(onDown, this);
function onDown(object, pointer)
{
// on down function
}

Related

Using Close Command in Method

I am trying to fire a command to close my page after finalizing the execution of a method. However, the Close() command is not working.
According to the code below, how do I close my view after finishing the method execution?
My Model:
public IMvxCommand BtnSaveCommand
{
get
{
return new MvxAsyncCommand(updateOrder);
}
}
private async Task<bool> updateOrder()
{
var errors = validator.Validate(this);
if (!errors.IsValid)
{
messageService.showMessage(errors);
return false;
}
var responseEdit = await orderService.update(configureOrder());
if (responseEdit == null)
{
messageService.showMessage("Pedido " + Item.id + " foi editado com sucesso.");
configureUpdateItem();
//Close View
Close(this);
}
else
{
messageService.showMessage((IErrorCollection)responseEdit);
}
return true;
}
--Update
Adding more information, when triggered the Close(this) command I get the following error:
Mvx: Warning: 325,38 Do not know how to close this viewmodel - topmost view does not present this viewmodel
You need to call DismissViewController() on the NavigationController

Identify true activeElement in a frame hierarchy

I'm looking for a way to get the focused input of any page with the goal to update it's value.
I have a content script that receives the value and checks if activeElement is an <input>.
The challenge is when the main document's activeElement is an iframe. I can set all_frames: true in manifest, which will find any active <input>, but I only want to set the value of the activeElement of the active iframe.
Currently I'm solving this by letting the child content script(s) blur() all activeElements except the current one (attaching a handler to focusin), but a solution that does not modify the document state would be better imho.
Is it possible to send a message only to the main document and if this one's activeElement is an iframe, get that frameId (and try again)?
I don't control the web pages.
Inject a new content script that checks the full hierarchy of frames, including cross-domain frames.
main content script asks the background/event page if needed:
if (document.activeElement.matches('input') && window == parent) {
console.log('Input', document.activeElement);
document.activeElement.value += ' gotcha!';
} else {
chrome.runtime.sendMessage({action: 'modifyInput'});
}
background/event page script executes the additional content script in all frames:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse)) {
if (msg.action == 'modifyInput') {
chrome.tabs.executeScript(sender.tab && sender.tab.id, {
file: 'modify-input.js',
allFrames: true,
matchAboutBlank: true,
runAt: 'document_end',
});
}
});
modify-input.js, IIFE is used to makes sure garbage collection removes the injected stuff.
;(function() {
if (isInputActive()) {
if (window == parent) {
foundTheInput();
} else {
askParent();
}
} else if (isFrameActive()) {
window.addEventListener('message', function onMessage(e) {
if (!e.data || e.data.id != chrome.runtime.id)
return;
switch (e.data.action) {
// request from a child frame
case 'checkme':
if (window == parent) {
confirmChild(e.source);
window.removeEventListener('message', onMessage);
} else {
askParent();
}
break;
// response from a parent
case 'confirmed':
window.removeEventListener('message', onMessage);
if (isInputActive()) {
foundTheInput();
} else if (isFrameActive()) {
confirmChild(e.source);
}
break;
}
});
}
function isInputActive() {
return document.activeElement.matches('input');
}
function isFrameActive() {
return document.activeElement.matches('frame, iframe');
}
function askParent() {
parent.postMessage({id: chrome.runtime.id, action: 'checkme'}, '*');
}
function confirmChild(childWindow) {
console.log('Frame', document.activeElement);
childWindow.postMessage({id: chrome.runtime.id, action: 'confirmed': true}, '*');
}
function foundTheInput() {
console.log('Input', document.activeElement);
document.activeElement.value += ' gotcha!';
}
})();
I didn't test this, but did use and saw similar code previously.

Attach a Javascript function to an OOTB ribbon button

I want to attach a custom javascript function to the out of the box "Download a copy" ribbon button. This is to provide analytics for file downloads done through the ribbon button.
I tried this code, but it doesn't seem to work:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script>
_spBodyOnLoadFunctionNames.push("Trackdownloads");
function Trackdownloads(){
debugger;
$("a[id='Ribbon.Documents.Copies.Download-Large']").live( "click",
function() {
alert('hello');
}
);
}
</script>
Any idea how to get this to work?
Found a solution to my problem.
Actually, attaching a javascript function to the button is not the right way to implement this.
The correct implementation is to replace the OOTB button with a custom button, and call a custom javascript function to carry out the desired action.
http://msdn.microsoft.com/en-us/library/ff407619.aspx
If you do want to override a button in the ribbon. Creating a custom Page Component is a good idea. Example:
Type.registerNamespace('Company.Project.Ribbon.PageComponent');
Company.Project.Ribbon.PageComponent = function (PageComponentId) {
this._pageComponentId = PageComponentId;
Company.Project.Ribbon.PageComponent.initializeBase(this);
}
Company.Project.Ribbon.PageComponent.prototype =
{
_pageComponentId: "PageComponentIDHolder",
getId: function () {
return this._pageComponentId;
},
init: function () {
this._myCommandList = ['DownloadCopy'];
this._myHandledCommands = {};
this._myHandledCommands['DownloadCopy'] = Function.createDelegate(this, this.CMD1_Handler);
},
getFocusedCommands: function () {
return this._myCommandList;
},
getGlobalCommands: function () {
return this._myCommandList;
},
canHandleCommand: function (commandId) {
var canHandle = this._myHandledCommands[commandId];
if (canHandle)
return true;
else
return false;
},
handleCommand: function (commandId, properties, sequence) {
return this._myHandledCommands[commandId](commandId, properties, sequence);
},
isFocusable: function () {
return true;
},
CMD1_Handler: function (commandId, properties, sequence) {
alert('Download a copy-button was clicked');
}
}
Company.Project.Ribbon.PageComponent.registerClass('Company.Project.Ribbon.PageComponent', CUI.Page.PageComponent)
NotifyScriptLoadedAndExecuteWaitingJobs("/_layouts/custompagecomponents/PageComponent.js");
function init2() {
var instance = new Company.Project.Ribbon.PageComponent("ComponentID");
SP.Ribbon.PageManager.get_instance().addPageComponent(instance);
}
function init1() {
ExecuteOrDelayUntilScriptLoaded(init2, 'sp.ribbon.js');
}
ExecuteOrDelayUntilScriptLoaded(init1, '/_layouts/custompagecomponents/PageComponent.js');

Getting edit box text from a modal MFC dialog after it is closed

From a modal MFC dialog, I want to extract text from an edit box after the dialog is closed. I attempted this:
CPreparationDlg Dlg;
CString m_str;
m_pMainWnd = &Dlg;
Dlg.DoModal();
CWnd *pMyDialog=AfxGetMainWnd();
CWnd *pWnd=pMyDialog->GetDlgItem(IDC_EDIT1);
pWnd->SetWindowText("huha max");
return TRUE;
It does not work.
The dialog and its controls is not created until you call DoModal() and as already pointed, is destroyed already by the time DoModal() returns. Because of that you cannot call GetDlgItem() neither before, nor after DoModal(). The solution to pass or retrieve data to a control, is to use a variable in the class. You can set it when you create the class instance, before the call to DoModal(). In OnInitDialog() you put in the control the value of the variable. Then, when the window is destroyed, you get the value from the control and put it into the variable. Then you read the variable from the calling context.
Something like this (notice I typed it directly in the browser, so there might be errors):
class CMyDialog : CDialog
{
CString m_value;
public:
CString GetValue() const {return m_value;}
void SetValue(const CString& value) {m_value = value;}
virtual BOOL OnInitDialog();
virtual BOOL DestroyWindow( );
}
BOOL CMyDialog::OnInitDialog()
{
CDialog::OnInitDialog();
SetDlgItemText(IDC_EDIT1, m_value);
return TRUE;
}
BOOL CMyDialog::DestroyWindow()
{
GetDlgItemText(IDC_EDIT1, m_value);
return CDialog::DestroyWindow();
}
Then you can use it like this:
CMyDialog dlg;
dlg.SetValue("stackoverflow");
dlg.DoModal();
CString response = dlg.GetValue();
Open your dialog resource, right-click on the textbox and choose "Add variable", pick value-type and CString
In the dialog-class: before closing, call UpdateData(TRUE)
Outside the dialog:
CPreparationDlg dlg(AfxGetMainWnd());
dlg.m_myVariableName = "my Value";
dlg.DoModal();
// the new value is still in dlg.m_myVariableName
DoModal() destroys the dialog box before it returns and so the value is no longer available.
It's hard to tell why you are setting m_pMainWnd to your dialog. To be honest, I'm not really sure what you are trying to do there. That's bound to cause problems as now AfxGetMainWnd() is broken.
Either way, you can't get the dialog box's control values after the dialog has been destroyed.
I often use
D_SOHINH dsohinh = new D_SOHINH();
dsohinh.vd_kichthuoc=v_kichthuocDOC;
dsohinh.vd_sohinh=v_soluongDOC;
if(dsohinh.DoModal()==IDOK)
{
v_soluongDOC=dsohinh.vd_sohinh;
v_kichthuocDOC=dsohinh.vd_kichthuoc;
}
SetModifiedFlag(true);
UpdateAllViews(NULL);
With dsohinh is Dialog form that you want to get data to mainform .
After get data then call SetModifiedFlag(true) to set view data updated.
call UpdateAllViews(NULL) to Set data to mainform
This solution may seem long, meaning that so much code has been written for this seemingly small task.
But when we have a list or tree inside the child window where all the items are created in the child window
and the items have to be moved to the parent window,
then it makes sense.
This source code can easily create a window and transfer information from the window before closing to the parents.
//copy the two functions in your code
//1- bool peek_and_pump(void)
// template<class T,class THISCLASS>
//2- void TshowWindow(int id,T *&pVar,THISCLASS *ths)
//and make two member variable
// bool do_exit;
// bool do_cancel;
//in child dialog class.
//set true value in do_exit in child dialog for exit
CchildDialog *dlg;
template<class T,class THISCLASS>
void TshowWindow(int id,T *&pVar,THISCLASS *ths)
{
T *p=pVar;
if(!p)
p= new T;
if(p->m_hWnd)
{
p->SetForegroundWindow();
}
else
{
delete p;
p= new T;
if(!(p->m_hWnd && IsWindow(p->m_hWnd)))
{
p->Create(id,ths);
if(IsWindow(p->m_hWnd))
p->ShowWindow(TRUE);
}
}
pVar=p;
}
bool peek_and_pump(void)
{
MSG msg;
#if defined(_AFX) || defined(_AFXDLL)
while(::PeekMessage(&msg,NULL,0,0,PM_NOREMOVE))
{
if(!AfxGetApp()->PumpMessage())
{
::PostQuitMessage(0);
return false;
}
}
long lIdle = 0;
while(AfxGetApp()->OnIdle(lIdle++))
;
#else
if(::PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
#endif
return true;
}
void CparentPage::OnBnClick1()
{
if(dlg)
{
dlg->DestroyWindow();
}
TshowWindow<CchildDialog,CparentPage>(IDD_DIALOG_child,dlg,this);
dlg->GetDlgItem(IDC_EDIT_1)->SetWindowText("");
dlg->m_temp_window.EnableWindow(FALSE);//enable or disable controls.
dlg->UpdateData(false);//for to be done enable of disable or else.
dlg->do_exit=false;
dlg->do_cancel=false;
while(dlg->do_exit==false)
{
peek_and_pump();//wait for dlg->do_exit set true
}
if( dlg->do_cancel==false )
{
CString str1;
dlg->GetDlgItem(IDC_EDIT_1)->GetWindowText(str1);
//or other member variale of CchildDialog
//after finish all work with dlg then destroy its.
}
dlg->DestroyWindow();
}
void CchildDialog::OnBnClickedOk()
{
UpdateData();
OnOK();
do_exit=true;
do_cancel=false;
}
void CchildDialog::OnBnClickedCancel()
{
OnCancel();
do_exit=true;
do_cancel=true;
}

npruntime & addEventListener

I am writing a chrome plugin in which I want to register click event, means whenever we click on DOM window, the handler inside plugin will be called. For that I am using CPlugin class. The constructor is called from NPP_New(/argument/).
When I run the browser and click anywhere, I noticed that ScriptablePluginObject's HasProperty and GetProperty function called with identifier name "handleEvent".
I don't understand how to handle the event.
Can anyone guide me please?
/////////////CODE///////////////////
static NPIdentifier sFunction_id;
// Called from NPP_New()
CPlugin::CPlugin(NPP pNPInstance) :
m_pNPInstance(pNPInstance),
m_pNPStream(NULL),
m_bInitialized(FALSE),
m_pScriptableObject(NULL)
{
bool boRet;
NPError rv;
char szText[300];
LogMessage("CPlugin::CPlugin::Enter");
sFunction_id = NPN_GetStringIdentifier("handleEvent");
rv = NPN_GetValue(m_pNPInstance, NPNVWindowNPObject, &sWindowObj);
if (NPERR_NO_ERROR != rv)
{
LogMessage("CPlugin::CPlugin::NPN_GetValue() failed.");
}
NPObject *scriptObj = NPN_CreateObject(m_pNPInstance, GET_NPOBJECT_CLASS(ScriptablePluginObject));
if (!scriptObj)
{
LogMessage("CPlugin::CPlugin::NPN_CreateObject failed");
}
NPVariant params[3];
// arg0: event type
STRINGZ_TO_NPVARIANT("click", params[0]);
// arg1: listener
params[1].type = NPVariantType_Object;
params[1].value.objectValue = scriptObj;
// arg2: useCapture
params[2].type = NPVariantType_Bool;
params[2].value.boolValue = true;
NPIdentifier addEventListener_id = NPN_GetStringIdentifier("addEventListener");
NPVariant result_add;
// windowObject.addEventListener("click", listener, false);
if (!NPN_Invoke(m_pNPInstance, sWindowObj, addEventListener_id, &params[0], 3, &result_add))
{
LogMessage("CPlugin::CPlugin::NPN_Invoke for addEventListener failed");
}
NPIdentifier removeEventListener_id = NPN_GetStringIdentifier("removeEventListener");
NPVariant result_remove;
// windowObject.removeEventListener("click", listener, false);
if (!NPN_Invoke(m_pNPInstance, sWindowObj, removeEventListener_id, &params[0], 3, &result_remove))
{
LogMessage("CPlugin::CPlugin::NPN_Invoke for removeEventListener failed");
}
NPN_ReleaseVariantValue(&result_add);
NPN_ReleaseVariantValue(&result_remove);
NPN_ReleaseObject(scriptObj);
const char *ua = "This is test plugin";//NPN_UserAgent(m_pNPInstance);
strcpy(m_String, ua);
LogMessage("CPlugin::CPlugin::Exit");
}
// In HasProperty and GetProperty, nothing has been done.
bool
ScriptablePluginObject::HasProperty(NPIdentifier name)
{
LogMessage("ScriptablePluginObject::HasProperty");
char *nam = NPN_UTF8FromIdentifier(name);
LogMessage(nam);
NPN_MemFree(nam);
return true;
}
bool
ScriptablePluginObject::GetProperty(NPIdentifier name, NPVariant *result)
{
LogMessage("ScriptablePluginObject::GetProperty");
char *nam = NPN_UTF8FromIdentifier(name);
LogMessage(nam);
NPN_MemFree(nam);
return true;
}
///////////CODE///////////
Both of the above classes are taken from google code. I am only adding event listener on NPObject.
What is wrong with it? Any idea?
-Abhay
Your on the track, but you require some more changes:
Create a brand new NPClass, you can name this MouseClickEvent or some sort.
Implement your mouse event listener functionality in the InvokeDefault of the MouseClickEvent class.
Now with NPN_CreateObject create your NPObject from the instance of MouseClickEvent
You pass that NPObject as a second parameter to the addEventListener you mentioned above.
Hope that helps!

Resources