How to trigger Angular handlers programmatically? - javascript

I have a form element with an ng-change handler. I want to programmatically trigger the handler, but without direct inspection of scope. I want to do this because I'm writing a Chrome extension so I can't easily access '$scope' to get the handler.
I have tried the obvious choice of
$(element).triggerHandler('change')
but that doesn't seem to work. See example here: https://plnkr.co/edit/iaz7trxVT09XWBktGhE9?p=preview (in this example I'm logging some lines to console when the change handler runs, but clicking the button doesn't log those lines).
I tried a few other methods found in various threads here, such as trigger() or manual construction of event and fire with dispatchEvent but to no avail. I don't quite understand why the event handler isn't triggering. Can anyone help?

Well, apparently (according to docs), the model change will not be triggered when the value is not changed. An ugly (yet effective) workaround would be to actually change the value briefly:
var v = $('#testField1').val();
$('#testField1').val(0)
$('#testField1').triggerHandler('change');
$('#testField1').val(v)
$('#testField1').triggerHandler('change');
Of course this will trigger the event twice, if this is a problem you could for example use a known "magic value" (e.g. min negative integer) and ignore it.
Alternatively, I'm afraid there is no simple solution: you might need to access the scope / controller to invoke the function you want directly or meddle with angular's event handling.

Related

Invoke the default action of a specific event on an object

I want a generic (cross browser) way to get the browser to execute the default action for an object for a specified event preferably without getting any attached listeners to fire.
This kind of question has been asked before but in the context of already being in an event, &/or strictly talking about synchronously holding off the default action before letting it happen later.
Basically, let's say you have an DOM element (you don't know which) variable, and you want to invoke a click, such that if it were an anchor, it'd follow its href, if it were an input[type="submit"] it would submit the form.
But without firing that element's listeners for the click event (which may be prone preventDefault()s in the listeners).
For those that need a reason to answer questions; you may want to do it if you're implementing something like dispatchEvent() for browsers that only have fireEvent().
Both functions return true if the default wasn't 'prevented', but only dispatchEvent() actually follows through and invokes the default.
As a side question, jQuery's trigger() is meant to do this (although after firing the listeners) and be cross-browser, maybe the solution is there? As nice as jQuery is I'd like to know the vanilla methods it is calling (if it [this particular feature] indeed works on things like IE8).
It appears that, at least for the click event, you can call .click() on the element in these browsers.
This will have the element enact the default (as well as calling all listeners and the .onclick value, if defined).
I don't know of any other defaults on DOM elements, would scroll need to be accounted for? Keypress? Maybe those exist as functions too, but I haven't tested.
When I did test .click(), I noticed it obeyed any of the listeners returning false and did not fire the default, and the event did bubble (a listener I had on document fired too!).
There may be no other alternative (I.e. calling the default directly, avoiding the listeners). And as for passing it an event object, the browser in question has the single global event thing going on, so maybe you can manipulate that and it wont have changed when executing .click().
Adding as I find more information in my travels :)
Furthermore, there is an doScroll() function, but I think it would be really hard to translate a given event into the string accepted by this method

In jQuery how can you attached change events to regular objects

How can you bind a change (or add/remove) event to a object or collection of objects to see see if it has changed using jQuery. I have looked around but can't seem to find much on the subject, yet it seems like a fairly standard use case.
You can bind an event handler for any event you like to any element you like, but it will only be called if the event actually is triggered. As there is no change event defined for anything other than form fields, nothing will happen unless you trigger the event yourself.
As Guffa pointed out, there is no change event in regular object, but input, textarea, and select. So you have to make your own content-change event. This article has how-to. http://james.padolsey.com/javascript/monitoring-dom-properties/ Read the last part.

Protect jQuery function from outside access

I'm using jQuery in an app which registers user clicks to perform a given action through the .click() binding, and I want this functionality to be available only through a user mousedown. One of my friends pointed out today that it's possible to run $(element).click() from a javascript terminal in Firebug (or something similar), and achieve the same functionality as clicking on the element -- something I'd like to prevent. Any ideas on how to go about doing this? Thanks for your input.
Short answer: No, you can't really prevent it.
Long answer: Any event like a click event is bound to such called Event handlers. Those handlers are functions which are executed when a given event occurs. So if you click on an element, your browser checks if any event handlers are bound to it, if so it fires them. If not, the browser will try to bubble up the event to the parent elements, again checks if there are any event handlers bound for that kind of event .. and so forth.
jQuerys .trigger() method (which is what you actually call if calling .click() for instance) just does the same thing. It calls the event handlers which are bound to a specific element, for a specific event.
EDIT
There might some simple ways to somekind of soft detect a real click, for instance you might check for the toElement property within an event object. That property is not set when triggered. But then again, you can easily fake that aswell with .trigger(). Example:
$(document).ready(function() {
$('#invalid2').bind('click', function(e){
alert('click\nevent.target: ' + e.toElement.id);
console.log(e);
});
$('#invalid1').bind('click', function(){
$('#invalid2').trigger({
type: 'click',
toElement: {id: 'Fake'}
});
});
});​
Working example: http://www.jsfiddle.net/v4wkv/1/
If you would just call $('#invalid2').trigger('click') the toElement property would not be there and therefore fail. But as you can see, you can add like anything into the event object.
What are you trying to prevent? Someone messing with your client side script? You can do things like obfuscate your code but not much other than that. But even doing this is just making it more hassle than it's worth in my opinion.
If you don't want people doing certain things move the functionality to the server.
Sorry to be bearer of bad news.
You cannot really do anything against it, it would also be possible to write the complete function and then fire it.
But why is this a problem? If somebody is changing something client side it only affects him. Or are you trying to check some data? This MUST always be done in the backend, because you can never be sure what is really sent to it.
You can check event object (which is passed as first argument to handler) originalEvent.
It will be undefined if event is simulated by .click()
But it's completely useless. You cannot use javascript for security - client has full control over it (and firebug console is just most obvious tool). Client-side security checks should be only hint for user and protection against errors, malicious input can be stopped on server-side only.

which HTML element lost focus?

in javascript, when I receive a focus event, how can I work out which element has lost focus? I'm trying to avoid having to put an onblur event handler on all elements within my web page.
#pbrodka: the target/srcElement property would refer to the element with focus for onfocus events
offhand I can't see a way to get this short of onblur, or if the set of objects you care about all have focus methods you could store a reference to that object instead. It's also possible event bubbling could get you out of jail
this all feels like a bit of a code smell though - perhaps you need to describe the problem in more detail
Difficult this. You cannot use event delegation to find out which control last produced a blur as focus/blur do not bubble up. There have been some attempts to 'fix' this but they are buggy and not resiliant cross browser.
Could I ask you why do you need this information as maybe there is an alternative solution.
Unfortunately, the onblur event doesn't bubble, otherwise you could have handled it at the window level to always know when an element lost focus.
As things are, I do believe it will be hard to do without, as you say, adding an onblur event handler to all elements (a truly nasty solution ;-).
It is possible to delegate the focus and blur events, if you follow PPK's advice, here:
http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
The most simple solution is to write a function that walks all forms and then all elements within the form and installs an onblur handler for each (which will probably call some global function). This handler will get an event and this event will contain the info you seek.
This way, you just have to call this method once in body.onload and it will work no matter how complex your document is.
The only drawback is that you will need to call it if you dynamically add forms to your current document. In this case, you must make sure not to install the handler again (or you will get spurious duplicate events).

JQuery detecting Programatic change event

If i do jQuery(expr).change( function), then I can get an event function to fire when the user makes a change to the value.
Is it possible to get this to fire if it's changed programatically, ie if I call jQuery(expr).val("moo").
or if some Plain old JavaScript changes it's value?
Thanks for any help.
After you've changed the value, you can fire the event yourself, and thus calling all the 'onchange' handlers.
jQuery('#element').change();
Changing the value directly in JS doesn't hook into anything which jQuery can listen for to trigger the change event. Like Sander says, you can fire the event handler yourself. If you don't have control over other code modifying these values and that isn't an option, you're kind of out of luck. The only other option which might work would be to have an observer watch the value on an interval using setTimeout, which is really messy and probably not a good idea.
jQuery v1+ supports the programmatic triggering of handlers - I have used this method as opposed to the .change() method as it allows for multiple other handlers to be fired if needed (e.g. some custom handlers). API Documentation is at: http://api.jquery.com/trigger/

Categories