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
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"
}
});
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 nodethis.$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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With