KnockoutJS data-bind setter

2019-08-29 13:15发布

问题:

Having a problem with HTML data-bind setter. I want it to set to model(exerciseCategories) intervals value. If I bind to intervals from model it is the right value but is not observable. If I bind it to $parent.intervals it is default value (1) from viewModel but it is observable. I want both :). What am I doing wrong? Something like this does work but displays [object Object]:

<td data-bind='with: exercise'>
   <input data-bind='value: $parent.intervals(intervals)' />
</td>

What I've got is - HTML    
            ...
            <td>
                <select data-bind='options: exerciseCategories , optionsText: "category", optionsCaption: "Izberite...", value: exerciseType'></select>
            </td>
            <td data-bind="with: exerciseType">
                <select data-bind='options: exercises, optionsText: "title", optionsCaption: "Izberite...", value: $parent.exercise'></select>
            </td>
            <td data-bind='with: exercise'>
                    <input data-bind='value: $parent.intervals' />
            </td>
            ...
 JavaScript
    var exerciseCategories = [
    {
        exercises: [{
            title: 'Aerobic exercise #1',
            intervals: 2
        }],
        category: 'Aerobics'
    }];

        var Exercise = function () {
                var self = this;

                self.exerciseType = ko.observable();
                self.exercise = ko.observable();
                self.intervals = ko.observable(1);
            };

回答1:

Doing $parent.intervals(intervals) you are invoking the intervals observable function passing intervals as a parameter, and obviously you'll receive the ko.observable object as a result.

I got your excerpt working. Take a look at this http://jsfiddle.net/MhHc4/

HTML

Categories:
<select data-bind='options: exerciseCategories , optionsText: "category", optionsCaption: "Izberite...", value: selectedCategory'></select>
<p>selectedCategory() debug: <pre data-bind="text: selectedCategory() ? ko.toJSON(selectedCategory().exercises, null, 2) : ''"></pre>
</p>Exercises:
<select data-bind='options: selectedCategory() ? selectedCategory().exercises : [], optionsText: "title", value: selectedExercise'></select>
<p>selectedExercise() debug: <pre data-bind="text: selectedExercise() ? ko.toJSON(selectedExercise(), null, 2) : 'x'"></pre>
</p>
<input type="text" data-bind="attr : { value : selectedExercise() ? selectedExercise().intervals : 0 }"/>

Javascript

var exerciseCategories = [{
    exercises: [{
        title: 'Aerobic exercise #1',
        intervals: 2
    }],
    category: 'Aerobics'
}];

var ExerciseViewModel = function () {
    var self = this;

    self.exerciseCategories = ko.observable(exerciseCategories);
    self.selectedCategory = ko.observable();
    self.selectedExercise = ko.observable();
    self.intervals = ko.observable(1);
};
ko.applyBindings(new ExerciseViewModel());

HTH



标签: knockout.js