简体   繁体   中英

Accessing elements inside a view - Backbone.JS


EDIT : SOLVED

Two typos in the code, one as stated and another sneaky one, Thanks alot and sorry for your time!

Hello SO,

My current issue occurred while exploring Backbone.js

I've created a simple HTML table using backbone, Each row is a model, The collection of all the rows is passed to a view that renders everything - so far, so good.

My table has the following classes : Each tablecell has a .tablecell class and each row has a .tablerow class.

I currently have a click event that fires correctly every time a table cell is clicked. What I'd like to figure out is how, if at all possible, can I access the 'clicked on' table cell and alter his attributes. As a simple example, Change the class of a clicked cell or change the background color.

Can it even be done? Or am I missing something completely?

My current thought is that each cell must be a model of his own with his own view and his own event, but I doubt it should be so complicated. Thanks in advance!

My single view is this :

            var rowView = Backbone.View.extend({

                //usual view attributes : el, model, initialize etc.

                events : 
                    {
                    "click.tablecell" : "clickOnCell",
                    },

                    clickOnCell : function(cell)
                    {
                        cell = $(cell.currentTarget);
                        cell.css("font-weight","bold");
                    },
                render : function () {

        // boring render method, renders correctly.

                },  
            });

You must add the event and handler to the events hash (you are missing a blankspace on your example):

events: { 'click .tablecell': 'clickOnCell' }

You receive the jQuery (or another framework you are replacing jQuery with) event object:

clickOnCell: function (e) {

    var $td = $(e.currentTarget);

    $td.css('color', 'red');

}

Understand that event delegation occurs at the end of view instantiation . By that, I mean that your view must have a the el property as your row.

If you cannot set el property during the view definition (which seems to be the case), try using setElement to your table row element during the render .

render: function () { 

   //...

   var myRow = $('<tr/>');

   this.setElement(myRow);        

   //...

}

Hope I've helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM