1

I'm trying to do a a Backbone calendar application. I have a model Event, an EventView and a DailyView.

The DailyView loads a template which contains a table with a list of cells that represents the hour (e.g.:td #09). I want to click the cell and obtain its id, but when I do, I fail. I think I'm referencing the el: div from DailyView instead of the td.

DailyView = Backbone.View.extend({
    tagName: "div",
    template: _.template($('#daily-view').html()),

    events: {
        'click td': 'onClick'
    },
    initialize: function(){
        _.bindAll(this, 'render');
        this.model.bind('change', this.render, this);
        this.render();
    },
    render: function(){
        $(this.el).html(this.template(this.model.toJSON()));

        return this;
    },
    onClick: function(){
        var hour= $(this.el).attr("id");
        //This doesn't work
    }

I've thought of adding the cells as sub-views (sometimes empty, sometimes containing an Event), but I don't like this approach and I'd prefer not to add more elemtns to the DOM unless it's strictly necessary.

Is there a way I can reference the td instead of the div?

  • First, the tagName property identifies the type of element you want your view to represent. So you'll need it to be 'td', not 'div'. Second, for your td to be part of a table, you'll have to add it to a table yourself. That means you'll need to add it to the table markup yourself. – kinakuta Apr 28 '13 at 20:58
  • There's no need to `$(this.el)` when you already have [`this.$el`](http://backbonejs.org/#View-$el). And there's no need for that `_.bindAll` if you're going to supply the third argument to the `this.model.bind()` call anyway. – mu is too short Apr 28 '13 at 21:24
  • @kinakuta No, the `div` is correct in that context. `DailyView` is the wrapper that contains the table (and the cells). `EventView` represents individual elements. The problem wasn't related to representing the table. @muistooshort Thanks, you are right. It's my first application with javascript (and jQuery and Backbone) and I need to clarify many concepts. – AnimusNecandi Apr 29 '13 at 07:40
  • @AnimusNecandi ah, I see - I mis-interpreted what you were trying to do. Glad you got it working. – kinakuta Apr 29 '13 at 20:36

1 Answers1

2

From this post: How to find the Id of model corresponding to clicked item?

onClick: function(e){
    var hour = e.currentTarget.id;
    //This does work ?
}
Community
  • 1
  • 1
Chris
  • 6,331
  • 1
  • 21
  • 25
  • It does! I guess I didn't search properly. I don't have enough reputation to upvote you, since I just made my account, but you just convinced me of the utility of participating in this site. Thank you very much :P – AnimusNecandi Apr 28 '13 at 21:06