了解Backbone.js事件处理程序

tha*_*way 4 javascript jquery backbone.js

所以这是我的观点:

$(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();
});
Run Code Online (Sandbox Code Playgroud)

我不明白的是如何更改el以使'this'接管我的全尺寸点击功能.我宁愿删除click jQuery函数并将鼠标悬停功能再次点击,但我似乎无法弄清楚如何将"this"分配给被点击的特定图像.我希望我的问题有道理.

Elf*_*erg 16

Backbone的事件处理程序假定您想要了解View.el每个事件的对象(包括其代码及其DOM表示,对象),并且该事件旨在更改视图和/或模型的某些方面.点击的实际目标是您假设知道或假设能够推导出来的.

推导相当简单:

fullsize: function(ev) {
    target = $(ev.currentTarget);
Run Code Online (Sandbox Code Playgroud)

this.在您的通话中替换您的所有参考target.. this.将继续引用该View实例.在你的内部函数,匿名一个分配.drop-shadow,this.将引用刚点击的对象.如果要访问周围的上下文,请使用闭包转发惯用法:

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
Run Code Online (Sandbox Code Playgroud)

  • 一个常见的替代方法是使用`_.bind()`方法(由backbone的依赖,underscore.js提供)将内部函数绑定到`this`(View对象)并使用`ev.currentTarget`,而不是`self/this`把戏. (2认同)