最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - In Backbone.js event callback what is this, and how do I get access to the element triggered? - Stack Overflow

programmeradmin0浏览0评论

I wonder why the this or $(this) selector isnt working when attaching functions to events in Backbone js. Look at this example code:

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...")
        }
    }
});

It is not working and it only works if I do this:

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...")
        }
    }
});

Isn't that a bit of an overkill can it be done with this or $(this)?

Thanks

I wonder why the this or $(this) selector isnt working when attaching functions to events in Backbone js. Look at this example code:

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...")
        }
    }
});

It is not working and it only works if I do this:

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...")
        }
    }
});

Isn't that a bit of an overkill can it be done with this or $(this)?

Thanks

Share Improve this question edited Jun 25, 2015 at 15:23 Evan Carroll 1 asked May 24, 2012 at 13:27 onlineracoononlineracoon 2,9705 gold badges48 silver badges66 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

In backbone.js "this" is bound to the view object.

If you need to access the target element you can still do so through the event.target or event.targetElement. Have a look at this question Backbone.js Event Binding

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论