Search code examples
javascriptbackbone.jsmarionette

Marionette CompositeView in the select>option context


I'm trying to set up a simple Marionette's CompositeView. Here's what I want in the end:

%select#target-id
  %option{:value => "#{@id}"} = @name
  %option{:value => "#{@id}"} = @name 
  etc

In my CompositeView I specify the childViewContainer: select and I need to display both @name (for the readability) and @id (for the related event) in the options of this select. Due to the nature of default div element I can to speficfy tagName as option in my ItemView:

class New.TargetView extends App.Views.ItemView
    template: "path/to/template"
    tagName: 'option'

And in the template I can pass only the content of to-be-created option element: = @name. This works fine, Marionette creates an option element for each model and populates it with the name of the model. The problem is that I don't know how to pass an attributes as well, since I can't specify an attribute of the element that hasn't been created yet.

I've also tried to set an attributes property on the ItemView like this:

attributes:
    value: "#{@id}"

And it technically works: the options are populated with the value="" attribute, but the content is undefined. Please advice.


Solution

  • I'm not sure about part when you use attributes. You should pass hash or function that will return hash as stated in Backbone view.attributes docs.

    attributes:
        value: "#{@id}"
    

    In old money it works like this. Here is jsfiddle.

    attributes: function () {
        return {
            value: this.model.id
        };
    }