user2109254
user2109254

Reputation: 1759

How to bind a (basic) Kendo DropDownList made from a select element, with data in option elements, to a javascript object using Kendo MVVM?

I can't seem to work out, or see examples any where in the doco or on the web for how to do this.

I have a simple select element that I have marked up to be a Kendo DropDownList.

HTML:

<div id="View">
    <select
    id="DropDownList"
    data-role="dropdownlist"
    data-value-primitive="true"
    data-bind="value: OptionID">
        <option value="1">Option One</option>
        <option value="2">Option Two</option>
        <option value="3">Option Three</option>
    </select>
</div>

JavaScript:

$(document).ready(function() {
    var oDataSource = {
        OptionID: -1
    };
    // MVVM Bind View to Record
    kendo.bind($('#View'), oDataSource);
    // Log OptionID set in oDataSource by DropDownListing Binding
    $('#DropDownList').data('kendoDropDownList').bind('select', function (e) {
        console.log('Selected Option: ' + oDataSource.OptionID);
    });
});

The console.log of the oDataSource.OptionID shows -1 every time.

I have created a fiddle here that demonstrates the code above: http://jsfiddle.net/codeowl/CDrFS/3/

What am I doing wrong?

Regards,

Scott

Upvotes: 0

Views: 726

Answers (1)

OnaBai
OnaBai

Reputation: 40887

Two questions:

  1. You should define oDataSource as an ObservableObject otherwise your variable is not bound to DropDownList.
  2. You need to use change handler instead since select is triggered when the option is selected but the input is not changed yet.

So your code should be:

var oDataSource = kendo.observable({
    OptionID: -1
});

// MVVM Bind View to Record
kendo.bind($('#View'), oDataSource);

// Log OptionID set in oDataSource by DropDownListing Binding
$('#DropDownList').data('kendoDropDownList').bind('change', function (e) {
    console.log('Selected Option: ' + oDataSource.OptionID);
});

See you JSFiddle modified here : http://jsfiddle.net/OnaBai/CDrFS/4/

Upvotes: 1

Related Questions