Rishi
Rishi

Reputation: 1349

How do I handle a click event on a specific target in backbone js

html file

<div class="work">
    <ul id="palette" class="palette-pen" style="top:178px;"> 
        <li class="palette-colour-1"><span></span></li>
        <li class="palette-colour-2"><span></span></li>
        <li class="palette-colour-3"><span></span></li>
        <li class="palette-colour-4"><span></span></li>
        <li class="palette-colour-5"><span></span></li> 
        <li class="palette-colour-6"><span></span></li>
    </ul>
</div>

js file

VC.View.Workspace_Tool_Image = Backbone.View.extend({
    events : {  
        'click .palette-pen li' : 'paint'
    },

    initialize : function() {
        var obj = this;

        /* scope */
        _.bindAll(this, 'paint');
    },

    paint: function() {
        var obj = this;
        $('ul.palette-pen li').click(function(e) { 
            alert(obj.$el.attr('class'));
        });
    },
})

I want to get the class of the specific li that I clicked, but when I click on an li the 1st time then it gives no alert. When I click a second time, it gives 1 alert with the div's class(work) rather than the class of the li that I clicked.

If I clicked on li nth time then it gives me n-1 alert. Why does this happen? Whether I clicked single time whether it is nth time or 7th time, it must give only one alert.

So please help me to find out the solution.

Upvotes: 2

Views: 556

Answers (1)

Smern
Smern

Reputation: 19066

It appears that everytime you click, you are adding a click listener that displays an alert. So the outcome makes sense. Since "paint" is only called when you click, just put your alert directly in that:

paint : function(e) {
    alert($(e.currentTarget).attr('class'));
},

Upvotes: 3

Related Questions