Understanding Backbone.js event handler - javascript

So here is my view:
$(function() {
var ImageManipulation = Backbone.View.extend({
el: $('body'),
tagName: "img",
events: {
'mouseover img': 'fullsize',
'click img#current': 'shrink'
},
initialize: function() {
_.bindAll(this, 'render', 'fullsize', 'shrink');
//var message = this.fullsize;
//message.bind("test", this.fullsize);
},
render: function() {
},
fullsize: function() {
console.log("in fullsize function");
console.log(this.el);
$('.drop-shadow').click(function() {
console.log(this.id);
if (this.id != 'current') {
$('.individual').fadeIn();
$(this).css('position', 'absolute');
$(this).css('z-index', '999');
$(this).animate({
top: '10px',
height: '432px',
}, 500, function() {
this.id = "current";
console.log("animation complete");
return true;
});
};
});
},
shrink: function() {
$('.individual').fadeOut();
$('#current').animate({
height: '150px',
}, 500, function() {
this.id = "";
$(this).css('position', 'relative');
$(this).css('z-index', '1');
console.log("animation complete");
return true;
});
}
});
var startImages = new ImageManipulation();
});
What I don't understand is how to change the el to make 'this' take over the click function I have in full-size. I would much rather have the click jQuery function removed and have the mouseover function be another click, but I cant seem to figure out how to assign 'this' to the particular image that is being clicked. I hope my question makes sense.

Backbone's event handler assumes that you want to know about the object (both its code, and its DOM representation, the View.el object) for every event, and that the event is intended to change some aspect of the view and/or model. The actual target of the click is something you're assumed to know, or assumed to be able to derive.
Derivation is rather simple:
fullsize: function(ev) {
target = $(ev.currentTarget);
And replace all your this. references within your call to target.. this. will continue to refer to the View instance. In your inner function, the anonymous one assigned to .drop-shadow, this. will refer to the object that was just clicked on. If you want access to the surrounding context, use the closure forwarding idiom:
fullsize: function(ev) {
var target = ev.currentTarget;
var self = this;
$('.drop-shadow').click(function(inner_ev) {
console.log(this.id); // the same as inner_ev.currentTarget
console.log(self.cid); // the containing view's CID

Related

Is it possible to bind multiple functions to multiple delegation targets in one place?

As it is possible to define multiple event handlers in one single function in jQuery like this:
$(document).on({
'event1': function() {
//do stuff on event1
},
'event2': function() {
//do stuff on event2
},
'event3': function() {
//do stuff on event3
},
//...
});
Then again we can do this:
$(document).on('click', '.clickedElement', function() {
//do stuff when $('.clickedElement') is clicked
});
I was wondering if it is also possible to do something like this (the following code does not work, it's just for illustration):
$(document).on('click', {
'.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
},
'.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
},
//... and so on
});
This code gives me an error complaining about the "," after '.clickedElementX'. I also tried it like this:
$(document).on('click', {
'.clickedElement1': function() {
//do stuff when $('.clickedElement1') is clicked
},
//... and so on
});
Then I don't have the error but also the function is not executed. Is there a way to collect all the click handlers in one place like this or would I have to always do it like this:
$(document).on('click', '.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
});
$(document).on('click', '.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
});
//... and so on
You can chain :
$(document).on({
click: function() {
//click on #test1
},
blur: function() {
//blur for #test1
}
}, '#test1').on({
click: function() {
//click for #test2
}
}, '#test2');
FIDDLE
Short answer: no, you have to bind them all separately.
Long answer: You can create an "infrastructure" for your site and have all events in one place. e.g.
var App = function(){
// business logic
return {
Settings: { ... },
Events: {
'event1': function(){
},
'event2': function(){
},
'event3': function(){
}
}
}
}();
Then wiring it up involves:
$(document).on(App.Events);
Then internally you can add then new bindings to your App object but still remains wired up in only one place (as far as jQuery is concerned). You could then make some kind of subscriber model within App (e.g. App.Subscribe('click', function(){ ... })) and each new subscription still is only wired through the single .on() binding.
but, IMHO, this is a lot of overhead with very little pay-off.
$(document).on('click' , function(e){
if($(e.target).hasClass("some-class")){
//do stuff when .some-class is clicked
}
if($(e.target).hasClass("some-other-class")){
//do stuff when .some-other-class is clicked
}
});
you can choose any some-class you want
It can be easily done, really:
$(document).ready(function()
{
$(this).on('click', '.one, .two',function()
{
if ($(this).hasClass('one'))
{//code for handler on .one selector
console.log('one');
}
else
{//code for handler on .two selector
console.log('two');
}
console.log(this);//code for both
});
});
If multiple events is what you're after:
$(document).ready(function()
{
$(this).on('click focus', '.one, .two',function()
{
if (event.which === 'click')
{
if ($(this).hasClass('one'))
{
console.log('one');
}
else
{
console.log('two');
}
}
else
{
console.log('focus event fired');
}
console.log(this);
});
});
Play around with this: here's a fiddle
documentation on event
jQuery's on, which is used here as though it were delegate
you can use a helper function:
function oneplace(all){
for (var query in all){
$(query).on('click', all[query]);
}
}
and then call:
oneplace(
{'#ele1':function(){
alert('first function');
},
'#ele2':function(){
alert('second function');
}});
jsfiddle here: http://jsfiddle.net/5zwkf/

Accessing Table Row From Popover

I currently have a bootstrap popover holding a button. The popover shows only when the mouse is over a table's tr.
What I want to do is to be able to access the elements for that row, is this possible.
Popover code:
$('.popup').popover(
{
placement: 'top',
trigger: 'manual',
delay: { show: 350, hide: 100 },
html: true,
content: $('#shortcuts').html(),
title: "Quick Tasks"
}
).parent().delegate('#quickDeleteBtn', 'click', function() {
alert($(this).closest('tr').children('td').text()); // ???
});
var timer,
popover_parent;
function hidePopover(elem) {
$(elem).popover('hide');
}
$('.popup').hover(
function() {
var self = this;
clearTimeout(timer);
$('.popover').hide(); //Hide any open popovers on other elements.
popover_parent = self
//$('.popup').attr("data-content","WOOHOOOO!");
$(self).popover('show');
},
function() {
var self = this;
timer = setTimeout(function(){hidePopover(self)},250);
});
$(document).on({
mouseenter: function() {
clearTimeout(timer);
},
mouseleave: function() {
var self = this;
timer = setTimeout(function(){hidePopover(popover_parent)},250);
}
}, '.popover');
HTML:
<div class="hide" id="shortcuts">
Delete
</div>
javascript that implements popover on row:
rows += '<tr class="popup datarow" rel="popover">';
Does anyone know what I'm doing wrong here and how I am supposed to access the child elements of the tr I'm hovering over?
JSFiddle: http://jsfiddle.net/C5BjY/8/
For some reason I couldn't get closest() to work as it should. Using parent().parent() to get to the containing .popover divider, then using prev() to get the previous tr element seems to do the trick however.
Just change:
alert($(this).closest('tr').children('td').text());
To:
alert($(this).parent().parent().prev('tr').children('td').text());
JSFiddle example.
As a side note, as your Fiddle uses jQuery 1.10.1 you should change delegate() to on():
on('click', '#quickDeleteBtn', function(index) { ... });
Here I have fixed it.
You just have to pass the container option in which the popover element is added for the popover
$('.popup').each(function (index) {
console.log(index + ": " + $(this).text());
$(this).popover({
placement: 'top',
trigger: 'manual',
delay: {
show: 350,
hide: 100
},
html: true,
content: $('#shortcuts').html(),
title: "Quick Tasks",
container: '#' + this.id
});
});
In your button click alert, $(this) refers to the button itself. In the DOM hierarchy, the popover html is nowhere near your hovered tr.
Add a handler to the list item to store itself in a global variable and access that from the click event. See the forked fiddle here.
First we declare a global (at the very top):
var hovered;
Then we add a mouseover handler to the list item. Note that using 'on' means every newly generated list item will also receive this handler:
$('body').on('mouseover', '.popup', function() {
hovered = $(this);
});
Then we can alert the needed data from within the button click event:
alert(hovered.text());
See here JS Fiddle
by removing the delegate and using the id to find the button and attaching it to a click handler by making the popover makes it easier to track it
$(self).popover('show');
$('#quickDeleteBtn').click(function(){
alert($(self).text());
});
also note
$('#shortcuts').remove();
because you were using the button in the popover with the same ID in the #shortcuts we couldn't select it first, now we remove it we can
You already have the correct element in your code. Just reuse the popover_parent variable and you are all set :) FIDDLE
alert($(popover_parent).text());
Or you could do something around like this :
$('.popup').hover(
function () {
var self = this;
clearTimeout(timer);
$('.popover').hide(); //Hide any open popovers on other elements.
$('#quickDeleteBtn').data('target', '');
popover_parent = self;
//$('.popup').attr("data-content","WOOHOOOO!");
$('#quickDeleteBtn').data('target', $(self));
$(self).popover('show');
},
function () {
var self = this;
timer = setTimeout(function () {
$('#quickDeleteBtn').data('target', '');
hidePopover(self)
}, 250);
});
$(document).on({
mouseenter: function () {
clearTimeout(timer);
},
mouseleave: function () {
var self = this;
timer = setTimeout(function () {
$('#quickDeleteBtn').data('target', '');
hidePopover(popover_parent)
}, 250);
}
}, '.popover');
I just store the element clicked in your #quickDeleteBtn then use the link.
FIDDLE HERE

Update available drop targets after dragstart fires in jquery.event.drag

Overview:
I have a page which uses jquery.event.drag and jquery.event.drop.
I need to be able to drag and drop onto elements which are constantly being added to the dom, even after the drag has started.
Problem:
When the dragstart event fires it checks for available drop targets and adds them to the drag object.
The problem I have is I am adding drop targets dynamically, after the dragstart event has fired, and therefore the user cannot drop onto these dynamically added drop targets.
Example:
http://jsfiddle.net/blowsie/36AJq/
Question:
How can I update the drag to allow dropping on elements which have been added to the dom after drag has started?
You can use this snippet.
The important function is: $.event.special.drop.locate();
Tested on chrome/safari/firefox/ie9 and seems to work.
SEE DEMO
UPDATE
For overlapping events, see if following code works. I set it inside an anonymous function just to avoid any global variable.
Idea is to use currentTarget property of event to check if not the same element is triggering same event. I set an id on newdrop element just in purpose of test here.
SEE UPDATED DEMO
(function () {
var $body = $("body"),
newdrops = [],
currentTarget = {},
ondragstart = function () {
$(this).css('opacity', .75);
}, ondrag = function (ev, dd) {
$(this).css({
top: dd.offsetY,
left: dd.offsetX
});
}, ondragend = function () {
$(this).css('opacity', '');
for (var i = 0, z = newdrops.length; i < z; i++)
$(newdrops[i]).off('dropstart drop dropend').removeClass('tempdrop');
newdrops = [];
}, ondropstart = function (e) {
if (currentTarget.dropstart === e.currentTarget) return;
currentTarget.dropstart = e.currentTarget;
currentTarget.dropend = null;
console.log('start::' + e.currentTarget.id)
$(this).addClass("active");
}, ondrop = function () {
$(this).toggleClass("dropped");
}, ondropend = function (e) {
if (currentTarget.dropend === e.currentTarget) return;
currentTarget.dropend = e.currentTarget;
currentTarget.dropstart = null;
console.log('end::' + e.currentTarget.id)
$(this).removeClass("active");
};
$body.on("dragstart", ".drag", ondragstart)
.on("drag", ".drag", ondrag)
.on("dragend", ".drag", ondragend)
.on("dropstart", ".drop", ondropstart)
.on("drop", ".drop", ondrop)
.on("dropend", ".drop", ondropend);
var cnt = 0;
setInterval(function () {
var dataDroppables = $body.data('dragdata')['interactions'] ? $body.data('dragdata')['interactions'][0]['droppable'] : [];
var $newDrop = $('<div class="drop tempdrop" id="' + cnt + '">Drop</div>');
cnt++;
$("#dropWrap").append($newDrop);
var offset = $newDrop.offset();
var dropdata = {
active: [],
anyactive: 0,
elem: $newDrop[0],
index: $('.drop').length,
location: {
bottom: offset.top + $newDrop.height(),
elem: $newDrop[0],
height: $newDrop.height(),
left: offset.left,
right: offset.left + $newDrop.width,
top: offset.top,
width: $newDrop.width
},
related: 0,
winner: 0
};
$newDrop.data('dropdata', dropdata);
dataDroppables.push($newDrop[0]);
$newDrop.on("dropstart", ondropstart)
.on("drop", ondrop)
.on("dropend", ondropend);
$.event.special.drop.locate($newDrop[0], dropdata.index);
newdrops.push($newDrop[0]);
}, 1000);
})();
I wasn't able to get this working using jquery.event.drag and jquery.event.drop, but I did make it work with the native HTML5 events:
http://jsfiddle.net/R2B8V/1/
The solution was to bind the events on the drop targets within a function and call that to update the bindings. I suspect you could get this working with jquery.event.drag and jquery.event.drop using a similar principal. If I can get those working I will update my answer.
Here is the JS:
$(function() {
var bind_targets = function() {
$(".drop").on({
dragenter: function() {
$(this).addClass("active");
return true;
},
dragleave: function() {
$(this).removeClass("active");
},
drop: function() {
$(this).toggleClass("dropped");
}
});
};
$("div[draggable]").on({
dragstart: function(evt) {
evt.originalEvent.dataTransfer.setData('Text', 'data');
},
dragend: function(evt) {
$('.active.drop').removeClass('active');
}
});
setInterval(function () {
$("#dropWrap").append('<div class="drop">Drop</div>');
// Do something here to update the dd.available
bind_targets();
}, 1000)
});
You can't. On dragstart, possible drop zones are calculated from the DOM, and can't be edited until dragend. Even constantly rebinding the .on() (Demo: http://jsfiddle.net/36AJq/84/) will not provide the desired effect.
I solved the issue a little differently. (Demo: http://jsfiddle.net/36AJq/87/)
Start with every <div> in the HTML.
Apply opacity: 0 to make it invisible, and width: 0 to keep it from getting a dropend when hidden.
Use setInterval to show the next hidden div ($('.drop:not(.visible)').first()) each 1000ms.
JS:
$("body")
.on("dragstart", ".drag", function () {
$(this).css('opacity', .75);
})
.on("drag", ".drag", function (ev, dd) {
$(this).css({
top: dd.offsetY,
left: dd.offsetX
});
})
.on("dragend", ".drag", function () {
$(this).css('opacity', '');
})
.on("dropstart", ".drop", function () {
$(this).addClass("active");
})
.on("drop", ".drop", function () {
$(this).toggleClass("dropped");
})
.on("dropend", ".drop", function () {
$(this).removeClass("active");
});
setInterval(function () {
$('.drop:not(.visible)').first()
.addClass('visible').removeClass('hidden');
}, 1000)
Enable the refreshPositions option.
Why not place all the divs into the page and set their visibility to hidden? Then use setInterval() to change each one's visibility every second.

Drop event in backbone view

I'm trying to add a drop event in my backbone view but I can't get it right. Below is the code I'm using and you can also check out this jsfiddle.
var View = Backbone.View.extend({
events: {
'drop .dropzone': 'drop'
},
drop: function(e) {
e.preventDefault();
alert('Dropping');
},
initialize: function() {},
render: function() {}
});
$(function() {
var view = new View({
el: $('.dropzone');
});
});​
if your view's el == .dropzone then you should do
events: {
'drop': 'drop'
},
if you specify just event type without selector it will listen to event on the view's root element - $('.dropzone') in this case.
The way you did it here would try to find .dropzone element among children of .dropzone element - and clearly it would fail to find this element at all

javascript 'this' issue: programmatically hide jQuery spotlight

I'm trying to augment the (very nice) jQuery Spotlight plugin so that I can programmatically invoke the "hide" behavior.
I've moved the related code into a hide() function, and it works fine when invoked from within spotlight itself. But when I try to invoke it from outside of spotlight nothing happens. I've checked that spotlight.hide is in fact defined to type function, but invoking it seemingly does nothing.
(function($) {
$.fn.spotlight = function(options) {
var hide = function() {
alert('hiding...'); /* never gets invoked when called from outside spotlight */
if(settings.animate){
spotlight.animate({opacity: 0}, settings.speed, settings.easing, function(){
if(currentPos == 'static') element.css('position', 'static');
element.css('z-index', '1');
$(this).remove();
// Trigger the onHide callback
settings.onHide.call(this);
});
} else {
spotlight.css('opacity', '0');
if(currentPos == 'static') element.css('position', 'static');
element.css('z-index', '1');
$(this).remove();
// Trigger the onHide callback
settings.onHide.call(this);
}
};
// Default settings
settings = $.extend({}, {
opacity: .5,
speed: 400,
color: '#333',
animate: true,
easing: '',
exitEvent: 'click',
onShow: function(){},
onHide: function(){}
}, options);
// Do a compatibility check
if(!jQuery.support.opacity) return false;
if($('#spotlight').size() == 0){
// Add the overlay div
$('body').append('<div id="spotlight"></div>');
// Get our elements
var element = $(this);
var spotlight = $('#spotlight');
// Set the CSS styles
spotlight.css({
'position':'fixed',
'background':settings.color,
'opacity':'0',
'top':'0px',
'left':'0px',
'height':'100%',
'width':'100%',
'z-index':'9998'
});
// Set element CSS
var currentPos = element.css('position');
if(currentPos == 'static'){
element.css({'position':'relative', 'z-index':'9999'});
} else {
element.css('z-index', '9999');
}
// Fade in the spotlight
if(settings.animate){
spotlight.animate({opacity: settings.opacity}, settings.speed, settings.easing, function(){
// Trigger the onShow callback
settings.onShow.call(this);
});
} else {
spotlight.css('opacity', settings.opacity);
// Trigger the onShow callback
settings.onShow.call(this);
}
// Set up click to close
spotlight.live(settings.exitEvent, hide);
}
// Returns the jQuery object to allow for chainability.
return this;
};
})(jQuery);
I install it with:
var spotlight = $('#media-fragment').spotlight({
opacity: .5,
speed: 400,
color: '#333',
animate: false,
easing: '',
exitEvent: 'click',
onShow: function(){},
onHide: function(){}
});
And then to hide it I do:
spotlight.hide();
I'm pretty sure that there is a scope or this issue involved.
Update: full solution at https://gist.github.com/2910643.
Try changing:
var hide = function() {
to:
this.hide = function() {
var defines the scope of the function or variable within the parent scope, i.e. it's essentially protected. this on the otherhand will explicitly set it on the parent object, prototype, and make it publicly accessible.

Categories

Resources