3

我想知道为什么 this 或 $(this) 选择器在将函数附加到 Backbone js 中的事件时不起作用。看这个示例代码:

var testView = Backbone.View.extend({
    el: $('#test'),
    events: {
        'keyup #signup-fullname': 'validateFullname'
    },
    validateFullName: function(e){
        if($(this).val() == "mike"){
            alert('You are just amazing!');
        } else if($(this).val() == "tom"){
            alert("mmm.. you fail...")
        }
    }
});

它不起作用,只有在我这样做时才起作用:

var testView = Backbone.View.extend({
    el: $('#test'),
    events: {
        'keyup #signup-fullname': 'validateFullname'
    },
    validateFullName: function(e){
        if($('#signup-fullname').val() == "mike"){
            alert('You are just amazing!');
        } else if($('#signup-fullname').val() == "tom"){
            alert("mmm.. you fail...")
        }
    }
});

可以用 this 或 $(this) 来完成,这不是有点矫枉过正吗?

谢谢

4

1 回答 1

11

在backbone.js 中,“this”绑定到视图对象。

如果您需要访问目标元素,您仍然可以通过 event.target 或 event.targetElement 进行。看看这个问题 Backbone.js Event Binding

于 2012-05-24T13:29:31.647 回答