Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

more flexible tagName in Backbone.js view

I am trying to force the 'multiple'='multiple' attribute on a select option tag view which is a Backbone view using jQuery selector with the attr function but I can't seem to make it work. Here's my code:

window.MyListView = Backbone.View.extend({

tagName:'select',
    className: 'mySelect',

initialize:function () {
},

render:function (eventName) {
    $(".mySelect").attr('multiple', 'multiple');
    _.each(this.model.models, function (myModel) {
        $(this.el).append(new MyListItemView({model:myModel}).render().el);
    }, this);
    return this;
} 

Not working at all. Any ideas or any other ways around this? Would I be better off creating a new view with only a select multiple tag and then append the myListItemView object to it?

Thanks a bunch, Jimmy

like image 981
Jimmy Luis Avatar asked Dec 01 '22 00:12

Jimmy Luis


2 Answers

You can provide any arbitrary attributes that you want for the view's tag using the 'attributes' attribute:


Backbone.View.extend({
  tagName: "select",
  attributes: {
    "multiple": "multiple"
  }
});
like image 121
Derick Bailey Avatar answered Dec 09 '22 19:12

Derick Bailey


Likely, the reason this is not working is that your view is not attached to the DOM yet, so $(".mySelect") is not finding the node.

When you want to operate on nodes in your view during, say, a render() method, you want to work with the view's el, there are a couple of helpers in Backbone to do that.

  • this.el - your view's root node
  • this.$el - a jquery object of your view's root node.
  • this.$({some selector}) - a jquery selector that starts at the root node.

This helpers will work on the view's nodes before they have been attached to the DOM (most commonly by the code that's creating the view in the first place.

So, your code, to add the multiple attribute would be

    window.MyListView = Backbone.View.extend({

        tagName:'select',
        className: 'mySelect',

        initialize:function () {
        },

        render:function (eventName) {
            this.$el.attr('multiple', 'multiple');
            return this;
        }
    });
like image 37
Edward M Smith Avatar answered Dec 09 '22 20:12

Edward M Smith