Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the element which triggered the event via backbone event handler

I have a view.

//define View
var CreatePollView = Backbone.View.extend({
    events: {
        "click #addOption": "addOption",
        "change .dynamicInput": "changeInputs"
    },
    initialize: function () {
        _.bindAll(this, "render", "addOption", "changeInputs");
        this.model.bind('change', this.render);
    },
    changeInputs: function () {
        var newVal = $(this).val(); // this throws exception in jquery script
        this.model.set("Subject", { Subject: newVal });
    }, ....

How can I access the element (it is an input element) on which the change event was triggered?

like image 255
Tom Avatar asked Oct 10 '11 15:10

Tom


1 Answers

You are getting an exception because you are calling _.bindAll on changeInputs. When you do that, you are saying that changeInputs will be bound to your object's context whenever it gets called.

In other words, when you refer to $(this) you are sending an instance of CreatePollView into jQuery, which it doesn't like.

You want to keep this binding, though, because you are accessing your model (this.model) so this needs to be the instance of CreatePollView.

Instead, you can get an event from your function and use the target or some other piece of information:

changeInputs: function(e) { }
like image 179
Brian Genisio Avatar answered Oct 16 '22 13:10

Brian Genisio