Kingisback
Kingisback

Reputation: 155

ID assigned to click event not working in backbone.js?

Below is my html and I have given ids to my all li's ..

<ul id="color_wrap">
    <li id="block4"></li>
</ul>

I'm novice to backbone.js. In my js file and in backbone.view part I have declared my code as shown below. I have given width and height to that li and when I click on it does not work. I want to make all li's clickable please help me where it is wrong, why its not working. When I click on li having id block4 it should call chooseColor function.

var SearchView = Backbone.View.extend({

    el: $("#search_container"),

    events: {
        "click #block4": "chooseColor",
        "focusout #search_input": "setDefaults"
    },

    chooseColor:function() {
        alert("hi");
    }

});

Upvotes: 4

Views: 3083

Answers (2)

Andreas K&#246;berle
Andreas K&#246;berle

Reputation: 110922

The problem is that all events added in the events block only listen to the element of the view not all elements in the page. So in your case # block4 is not a child element in the view.el element.

Take a look at the documented source code of backbone. There can you see that it use jQueries $el.on on the views element to bind the events.

Upvotes: 1

namero999
namero999

Reputation: 3002

As per your JSFiddle, it's not working because you are binding your events to SearchView that has search_container as root element. block4 is not a child of search_container and will never be matched. I would suggest to create another View that represent color_wrap. Your click event, if declared in such a view, will work.

Upvotes: 3

Related Questions