Jquery Event Listener for javascript objects - javascript-events

I apologize if this has been asked before but, is there a way to add an event listener/handler to a Javascript object? Preferably using JQuery.
Such as:
var foo;
$(foo).bind('change', function() {
alert("Foo has changed!");
});
I have tried this, but nothing seems to happen. Does this only work with DOM elements?
EDIT:
I need an event fired every time that the audio or video tags throw an error. Originally, I was using an interval to check whether or not the error, 'media.error', object was null, but this uses excess processing power and I would like to avoid it.
EDIT 2: Apparently I was going about it wrong, easiest way I found was to add the "onerror" property to the video/audio tag.

I agree with Cheeso that it's more important for you to state what you actually want to do, however one workaround for your specific question could be to store your variable within an object and only provide access through getter / setter, then you can do what you want in the setter. e.g.
function data() {
var foo = 0;
this.setFoo = function(newVal) {
foo = newVal;
alert(foo);
};
}
var theData = new data();
theData.setFoo(5);

Yes, that's correct. You cannot make a "variable watcher". There is no event fired for variables when they are changed.
What are you really trying to do?

You could try:
http://higginsforpresident.net/js/static/jq.pubsub.js
See
http://weblog.bocoup.com/publishsubscribe-with-jquery-custom-events
Or use a framework like backbone/underscore or knockout.js.

HTML/Elements/audio
var foo;
$(foo).bind('error', function() {
//your code here
});

Related

Can i get the template parent data context in the event function?

I'd love to get my hands on a templates data context.
Can I do something like this?
'click .newContext': function(event, template) {
var template_parent = template.parent();
var parent_data = template_parent.data;
}
You can use Template.parentData(0), the argument defines how deep you want to go, if you pass none, 0 is the default. Check the documentation on this: http://docs.meteor.com/#/full/template_currentdata
Yeah, if you're trying to get the parent's data context you should be able to use the parentData() method on the Template instance. You probably don't even need that second template parameter.
'click .newContext': function(event) {
var parent_data = Template.parentData();
}

map keyboard keys with mootools

I am looking to make the enter key behave exactly like the tab key on a form.
I am stuck on the fireEvent section.
var inputs = $$('input, textarea');
$each(inputs,function(el,i) {
el.addEvent('keypress',function(e) {
if(e.key == 'enter') {
e.stop();
el.fireEvent('keypress','tab');
}
});
});
How do I fire a keypress event with a specified key? Any help would be greatly appreciated.
this will work but it relies on dom order and not tabindex
var inputs = $$('input,textarea');
inputs.each(function(el,i){
el.addEvent('keypress',function(e) {
if(e.key == 'enter'){
e.stop();
var next = inputs[i+1];
if (next){
next.focus();
}
else {
// inputs[0].focus(); or form.submit() etc.
}
}
});
});
additionally, textarea enter capture? why, it's multiline... anyway, to do it at keyboard level, look at Syn. https://github.com/bitovi/syn
the above will fail with hidden elements (you can filter) and disabled elements etc. you get the idea, though - focus(). not sure what it will do on input[type=radio|checkbox|range] etc.
p.s. your code won't work because .fireEvent() will only call the bound event handler, not actually create the event for you.
Take a look at the class keyboard (MooTools More).
It can fire individual events for keys and provides methodology to disable and enable the listeners assigned to a Keyboard instance.
The manual has some examples how to work with this class, here's just a simple example how I implemented it in a similar situation:
var myKeyEv1 = new Keyboard({
defaultEventType: 'keydown'
});
myKeyEv1.addEvents({
'shift+h': myApp.help() // <- calls a function opening a help screen
});
Regarding the enter key in your example, you have to return false somewhere to prevent the enter-event from firing. Check out this SO post for more details.

jQuery — trigger a live event only once per element on the page?

Here's the scenario
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
}
})
Here's some background
The custom event is from a plugin called inview
The actual issue is here http://syndex.me
In a nutshell, new tumblr posts are being infnitely scrolled via
javascript hack (the only one out there for tumblr fyi.)
The inview plugin listens for new posts to come into the viewport, if the top of an image is shown, it makes it visible.
It's kinda working, but if you check your console at http://.syndex.me check how often the event is being fired
Maybe i'm also being to fussy and this is ok? Please let me know your professional opinion. but ideally i'd like it to stop doing something i dont need anymore.
Some things I've tried that did not work:
stopPropagation
.die();
Some solutions via S.O. didnt work either eg In jQuery, is there any way to only bind a click once? or Using .one() with .live() jQuery
I'm pretty surprised as to why such an option isnt out there yet. Surely the .one() event is also needed for future elements too? #justsayin
Thanks.
Add a class to the element when the event happens, and only have the event happen on elements that don't have that class.
$("p:not(.nolive)").live(event,function(){
$(this).addClass("nolive");
dostuff();
});
Edit: Example from comments:
$("p").live(event,function(){
var $this = $(this);
if ($this.data("live")) {
return;
}
$this.data("live",true);
doStuff();
});
This one works (see fiddle):
jQuery(function($) {
$("p").live('customEvent', function(event, chkSomething) {
//this particular custom event works with live
if (chkSomething) {
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).bind('customEvent', false);
}
});
function doStuff() {
window.alert('ran dostuff');
};
$('#content').append('<p>Here is a test</p>');
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
});
This should also work for your needs, although it's not as pretty :)
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething && $(this).data('customEventRanAlready') != 1){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).data('customEventRanAlready', 1);
}
})
Like Kevin mentioned, you can accomplish this by manipulating the CSS selectors, but you actually don't have to use :not(). Here's an alternative method:
// Use an attribute selector like so. This will only select elements
// that have 'theImage' as their ONLY class. Adding another class to them
// will effectively disable the repeating calls from live()
$('div[class=theImage]').live('inview',function(event, visible, visiblePartX, visiblePartY) {
if (visiblePartY=="top") {
$(this).animate({ opacity: 1 });
$(this).addClass('nolive');
console.log("look just how many times this is firing")
}
});
I used the actual code from your site. Hope that was okay.

Titanium Mobile: reference UI elements with an ID?

How do you keep track of your UI elements in Titanium? Say you have a window with a TableView that has some Switches (on/off) in it and you'd like to reference the changed switch onchange with a generic event listener. There's the property event.source, but you still don't really know what field of a form was just toggled, you just have a reference to the element. Is there a way to give the element an ID, as you would with a radiobutton in JavaScript?
Up to now, registered each form UI element in a dictionary, and saved all the values at once, looping through the dictionary and getting each object value. But now I'd like to do this onchange, and I can't find any other way to do it than create a specific callback function for each element (which I'd really rather not).
just assign and id to the element... all of these other solution CAN work, but they seem to be over kill for what you are asking for.
// create switch with id
var switcher0 = Ti.Ui.createSwitch({id:"switch1"});
then inside your event listener
myform.addEventListener('click', function(e){
var obj = e.source;
if ( obj.id == "switch1" ) {
// do some magic!!
}
});
A simple solution is to use a framework that helps you keep track of all your elements, which speeds up development quite a bit, as the project and app grows. I've built a framework of my own called Adamantium.js, which lets you use a syntax like jQuery to deal with your elements, based on ID and type selectors. In a coming release, it will also support for something like classes, that can be arbitrarily added or removed from an element, tracking of master/slave relationships and basic filter methods, to help you narrow your query. Most methods are chainable, so building apps with rich interaction is quick and simple.
A quick demo:
// Type selector, selects all switches
$(':Switch')
// Bind a callback to the change event on all switches
// This callback is also inherited by all new switch elements
$(':Switch').bind('change', function (e) {
alert(e.type + ' fired on ' + e.source.id + ', value = ' + e.value);
});
// Select by ID and trigger an event
$('#MyCustomSwitch').trigger('change', {
foo: 'bar'
});
Then there's a lot of other cool methods in the framework, that are all designed to speed up development and modeled after the familiar ways of jQuery, more about that in the original blog post.
I completely understand not wanting to write a listener to each one because that is very time consuming. I had the same problem that you did and solved it like so.
var switches = [];
function createSwitch(i) {
switches[i] = Ti.UI.createSwitch();
switches[i].addEventListener('change', function(e) {
Ti.API.info('switch '+i+' = '+e.value);
});
return switches[i];
}
for(i=0;i<rows.length;i++) {
row = Ti.UI.createTableViewRow();
row.add(createSwitch(i));
}
However keep in mind that this solution may not fit your needs as it did mine. For me it was good because each time I created a switch it added a listener to it dynamically then I could simply get the e.source.parent of the switch to interact with whatever I needed.
module Id just for the hold it's ID. When we have use id the call any another space just use . and use easily.
Try This
var but1 = Ti.Ui.createButton({title : 'Button', id:"1"});
window.addEventListener('click', function(e){
var obj = e.source;
if ( obj.id == "1" ) {
// do some magic!!
}
});
window.add(but1);
I, think this is supported for you.
how do you create your tableview and your switcher? usually i would define a eventListener function while creating the switcher.
// first switch
var switcher0 = Ti.Ui.createSwitch();
switch0.addEventListener('change',function(e){});
myTableViewRow.add(switch0);
myTableView.add(myTableViewRow);
// second switch
var switch1 = ..
so no generic event listener is needed.

making jQuery plug-in autoNumeric format fields by time page loads

I've been messing around with autoNumeric, a plug-in for jQuery that formats currency fields.
I'd like to wire the plug-in so that all currency fields are formatted by the time the user sees the page, e.g., on load.
Currently, the default that I can't seem to get around is that fields are formatted upon blur, key-up or other action in the fields themselves.
I've been experimenting with the plug-in code and it looks like it will take this relative newcomer some time to resolve this, if at all.
Anybody on this?
Lille
Triggering 'focusout' event formats the field. Triggering 'change' does not work in the most recent version (1.7.4).
$('input.money').autoNumeric({aNeg: '-'}).trigger('focusout');
autoNumeric does all formatting after 'onchange' event fires. So all that you need is to programmatically fire this event. Like this:
$('input.money').autoNumeric({aNeg: '-'}).trigger('change');
Hope this helps!
I just ran into this problem myself. I had to make it more general, but this worked for me:
$('input.auto-numeric').ready(function(){
var format_options = {
aSign: '$'
};
$('input.auto-numeric').each(function(){
$(this).autoNumeric(format_options);
if($(this).attr('id')){
$(this).val($.fn.autoNumeric.Format($(this).attr('id'), $(this).val(), format_options));
}
});
});
This should work.
jQuery(function($) {
$('input.auto').ready(function(){
$('input.auto').autoNumeric();
var inputID = uniqueID; // use the jQuery.get() function to retrieve data
var formatValue = '1234.00'; // use the jQuery.get() function to retrieve data
if(jQuery().autoNumeric){
$('#id').val($.fn.autoNumeric.Format(inputID, formatValue));
}
else{
alert('plugin not available');
}
});
});
Bob
This is what I eventually did:
$(document).ready(function(){
$('input.auto').autoNumeric();
$('input.auto').each(function(){
var element = this
if(element.value !=""){
$('#'+element.id).val($.fn.autoNumeric.Format(element.id, element.value));
}
}
);
});
Another way of forcing formatting is using 'update' like
$(".input-numeric").autoNumeric('update');
In the current version 2.* and onward, this is done by default thanks to the formatOnPageLoad option that is set to true.
It's that simple ;)

Resources