Select View

classes.SelectView is a wrapper for the Select.js library.

Simple Array Example

The SelectView can be implemented with a simple array. It will construct a Backbone Collection out of the array of values that you pass…

 1var select1 = new classes.SelectView({
 2    values: ["Rune","Fred","Zach","Steve"],
 3    helper: "Owner"
 4})
 5$('#simple-array').html(select1.render().el)
 6
 7// Listen for change events
 8select1.on("change", function (model) {
 9    console.log(model)
10    $('#simple-array').append(model.get('label'))
11})

Backbone Collection

To implement a SelectView with a Backbone Collection, you must pass both a collection and specify which attribute is to be the label.

 1var select2 = new classes.SelectView({
 2    collection: new Backbone.Collection([
 3        {first:"Rune", last:"Madsen"},
 4        {first:"Steve", last:"Klise"},
 5        {first:"Zach", last:"Schwartz"}
 6    ]),
 7    label: "first",
 8})
 9$('#collection-example').html(select2.render().el)
10
11// Listen for changes
12select2.on('change', function (model) {
13    $('collection-example').append(model.get('key'))
14})

You can also define a value that is different from the visible label, deactivate sorting of options and define a default option.

Get current value Get current model

 1var select2b = new classes.SelectView({
 2    collection: new Backbone.Collection([
 3        {name:"toc", prettyname:"Table of Contents"},
 4        {name:"chapter", prettyname:"Chapter"},
 5        {name:"sect1", prettyname:"Section1"},
 6    ]),
 7    label: "prettyname",
 8    value: "name",
 9    sort: false,
10    default_to: 'chapter'
11})
12$('#collection-example-b').html(select2b.render().el)
13
14// Listen for changes
15select2b.on('change', function (model) {
16    $('collection-example-b').append(model.get('key'))
17})

Adding a Model

Add a model to a select by using the add_model function and passing a Backbone Model as the only parameter. The model will be added and the list will be sorted alphabetically.

 1var select3 = new classes.SelectView({
 2    values: ["Rune","Fred","Zach","Steve"],
 3    helper: "Owner"
 4})
 5$('#add-model').html(select3.render().el)
 6
 7// Listen for change events
 8select3.on("change", function (model) {
 9    $('#simple-array').append(model.get('label'))
10})
11
12select3.add_model(new Backbone.Model({label:"Andrew"}))

Helpers

You can also add helper text!

 1var select4 = new classes.SelectView({
 2    collection: new Backbone.Collection([
 3        {name:"Rune", key:"madsen"},
 4        {name:"Steve", key:"klise"},
 5        {name:"Zach", key:"schwartz"}
 6    ]),
 7    helper: "NAMES!",
 8    label: "name",
 9})
10$('#helper-example').html(select4.render().el)