KnockoutJS数据绑定设置器

时间:2013-03-04 10:49:31

标签: knockout.js

HTML数据绑定设置器有问题。我希望它设置为model(exerciseCategories) interval 值。 如果我从模型绑定到间隔,那么它是正确的值,但是不可观察。 如果我将它绑定到$ parent.intervals,它是来自viewModel的默认值(1),但它是可观察的。 我想要两个:)。我究竟做错了什么? 这样的东西确实有效但显示[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 个答案:

答案 0 :(得分:0)

执行$ parent.intervals(interval)调用interval可观察函数传递interval作为参数,显然你会收到ko.observable对象。

我让你的节选工作了。看一下这个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