Understanding Backbone.js Event Handler

So here is my opinion:

$(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(); }); 

I don’t understand how to change el so that 'this' takes on the click function that I have in full size. I would prefer the jQuery function to be removed and the mouseover function to be deleted with another click, but I cannot figure out how to assign 'this' to the specific image click. Hope my question makes sense.

+4
source share
1 answer

The backbone event handler assumes that you want to know about the object (both its code and its DOM representation, View.el object) for each event, and that the event is intended to change some aspect of the view and / or model. The actual purpose of the click is what you expect to know or consider possible to receive.

The conclusion is pretty simple:

 fullsize: function(ev) { target = $(ev.currentTarget); 

And replace all your links with this. in your call to target. . this. will continue to reference the View instance. In your internal function, the anonymous assigned .drop-shadow , this. , will refer to an object that was just clicked. If you want to access the surrounding context, use the closure forward 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 CID 
+16
source

All Articles