理解Backbone.js事件处理程序

4
这是我的观点:
$(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();
});

我不明白的是如何更改el,使得“this”接管我在全尺寸中拥有的点击函数。我更希望删除click jQuery函数,并将mouseover函数作为另一个点击函数,但我似乎无法弄清如何将“this”分配给被单击的特定图像。希望我的问题表达清楚。


жҲ‘и®ӨдёәдҪ еҸҜиғҪйңҖиҰҒдҪҝз”ЁеәҸеҲ—еҢ–http://documentcloud.github.com/backbone/#View-extendпјҢеҗҢж—¶el: 'body'дёҚжҳҜ$('body')гҖӮеңЁе…¶дёӯдёҖдёӘзӨәдҫӢдёӯпјҢе®ғеҸҜиғҪжңҹжңӣе®ғжҳҜдёҖдёӘеӯ—з¬ҰдёІиҖҢдёҚжҳҜдёҖдёӘеҜ№иұЎгҖӮ - Val
1个回答

16

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

推导相当简单:

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

并且在调用target时替换所有的this.引用。 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

1
太棒了,解释得非常好!现在我的代码看起来更加简洁,我对Backbone的理解也更深入了! - pizza247
2
一个常见的替代方法是使用_.bind()方法(由backbone的依赖项underscore.js提供)将内部函数绑定到this(View对象),并使用ev.currentTarget,而不是self/this技巧。 - Elf Sternberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接