Jimmy Luis
Jimmy Luis

Reputation: 185

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

Upvotes: 4

Views: 2513

Answers (3)

Jimmy Luis
Jimmy Luis

Reputation: 185

The select 'multiple' problem is solved now but I've tried iterating with this.collection.each(myItem)... as suggested by Ed which looks like a cleaner solution than the underscore one but even though the item is there it does not render any of the items in the view:

/*_.each(this.model.models, function (myModel) {            
$(this.el).append(new   MyListItemView({model:myModel}).render().el);        }, this);  */  

this.collection.each(function(myItem){ 
             console.log(myItem.id);
             $(this.el).append(new MyListItemView({model:myItem}).render().el);
    }); 

I went to see the state of the arguments in MyListItemView but they're all ok. Any thoughts? Thanks

Upvotes: 0

Derick Bailey
Derick Bailey

Reputation: 72878

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"
  }
});

Upvotes: 10

Edward M Smith
Edward M Smith

Reputation: 10627

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 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;
        }
    });

Upvotes: 9

Related Questions