質問

html part

<input data-bind="kendoComboBox: { dataTextField: 'FirstName', dataValueField: 'PersonID',  data: AllUsers,template: '<span>#= data.FirstName # #= data.LastName # </span>',  value: SelectedUserID, 
change: UserSelectionChanged}" />

event handler inside model

var self= this;...    
self.UserSelectionChanged = function () {

        $.ajax({
            type: "POST",
            url: defaultUri + '/Home/GetUserTasks',
            data: JSON.stringify({ PersonID: self.SelectedUserID() }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (o) {
                self.SelectedUserTask(null);
                self.SelectedUserTask(o);
                //RRM: Added this line below so that whenever user dropdown is changed or refresh button is clicked in AssignedTo the first task of that particular user is Selected.
                self.selectTask(o[0]);

            }
        });
    };

here the event is being called but the data in self is not there. The event doesn't seems to be bind well with knockout. how to properly bind the ko event in the kendo combobox event?

役に立ちましたか?

解決

Instead of registring to the change event, I'd subscribe to SelectedUserID:

var self= this;
...
self.SelectedUserID.subscribe(function(selectedUserId) {

    $.ajax({
        type: "POST",
        url: defaultUri + '/Home/GetUserTasks',
        data: JSON.stringify({ PersonID: selectedUserId }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (o) {
            self.SelectedUserTask(null);
            self.SelectedUserTask(o);
            //RRM: Added this line below so that whenever user dropdown is changed or refresh button is clicked in AssignedTo the first task of that particular user is Selected.
            self.selectTask(o[0]);

        }
    });
});

This way it doesn't matter when or how the SelectedUserID is being changed.

他のヒント

As sroes wrote subscribing to the observable is the best choice here.

In cases where you have to bind to the kendo event then you can do this:

data-bind="... change: UserSelectionChanged(), ...."

Notice the function call parenthesis at the end ^

Now you function has to be like this:

this.UserSelectionChanged = function () {
    var self = this;

    return function(e) {
        $.ajax({ 
            self.blah ...
        });
    }
}

Now you have created a closure and you can access your view model using self but you also have the original Telerik event args inside e like e.dataItem etc.

So now you are unstoppable, you can do everything!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top