2
votes

I need to bind click events to certain amount of special divs, which divs should be binded are only known at runtime so I was thinking simply set a class for all these special divs and bind them in "events", but then click on one of these divs would trigger all divs to fire then I tried to use variables in events, but these variables are only know at runtime, so it turns out they are undefined when binding events now I am using jQuery to bind the events inside Backbone at runtime, but whenever I initialize the view, the event fires right away

var RoomNumber = Backbone.View.extend({
    el: $('#roomColumn' + this.roomNumber),
    initialize: function () {
        _.bindAll(this, 'render');
        this.user = this.options.user;
        this.roomNumber = this.options.roomNumber;
        this.render();
        //$('#roomNumber'+this.roomNumber).on('click', this.enterBooking());
    },
    render: function () {
        $(this.el).append("<div class = 'roomNumber' id  = 'roomNumber" + this.roomNumber + "'>" + this.roomNumber + "</div>");
    },
    enterBooking: function () {
        var slideForm = new SlideForm({
            user: this.user,
            roomNumber: this.roomNumber,
            state: 'book',
            singleSchedule: new Schedule()
        });
    }
});

Would anyone kindly explain why these would happen? And how can I bind events to a dynamically generated divs?

(I know I probably should not have used a backbone view like this..but it's part of requirements )

2
How are you generating the views? Could you include the code which calls new RoomNumber()? - Benjen

2 Answers

3
votes

Your code is having two problems:

  1. Answering to your point, events are triggered when binding because you are calling the event handler while binding.

    $('#roomNumber'+this.roomNumber).on('click', this.enterBooking());
    should be
    $('#roomNumber'+this.roomNumber).on('click', this.enterBooking);
    Notice the function call braces.

  2. The way you have set the el is wrong

    el: $('#roomColumn' + this.roomNumber),
    In backbone, el property of the view gets set before the initialize method gets called. This would mean that backbone would try to find for an element $('#roomColumnundefined') which is not expected. Instead, you can pass the el element as an option to the view

        var roomNumber = 3;
        var view = new RoomNumber({
            roomNumber:roomNumber,
            el:$('#roomColumn' + roomNumber)
        });
    
0
votes
......
//Pseudo code
render: function () {
    $(this.el).append("<div class = 'roomNumber' id  = 'roomNumber" + this.roomNumber + "'>" + this.roomNumber + "</div>");

    //you can dynamic set up events like this:
    this.events["click #roomNumber"+this.roomNumber] = "enterBooking";
    this.delegateEvents(this.events);

},
......