ko.subscribe儿童模型属性

Mat*_*nce 8 javascript data-binding mvvm viewmodel knockout.js

寻找如何在knockoutjs中设置子模型的一个很好的例子.这包括绑定到儿童事件,例如我尚未能够正常工作的属性更新.

此外,在这种情况下绑定到单个子节点而不是数组会更好,但我不知道如何在没有foreach模板的情况下在html中设置它.

http://jsfiddle.net/mathewvance/mfYNq/

谢谢.

<div class="editor-row">
    <label>Price</label>
    <input name="Price" data-bind="value: price"/>
</div>

 <div class="editor-row">
    <label>Child</label>
    <div data-bind="foreach: childObjects"> 
        <div><input type="checkbox" data-bind="checked: yearRound" /> Year Round</div>
        <div><input type="checkbox" data-bind="checked: fromNow" /> From Now</div>
        <div>
            <input data-bind="value: startDate" class="date-picker"/> to 
            <input data-bind="value: endDate" class="date-picker"/>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)
var ChildModel= function (yearRound, fromNow, startDate, endDate) {
    var self = this;

    this.yearRound = ko.observable(yearRound);
    this.fromNow = ko.observable(fromNow);
    this.startDate = ko.observable(startDate);
    this.endDate = ko.observable(endDate);

    this.yearRound.subscribe = function (val) {
        alert('message from child model property subscribe\n\nwhy does this only happen once?');

        //if(val){
        //    self.startDate('undefined');
        //    self.endDate('undefined');
        //}
    };
}

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

    this.price = ko.observable(1.99);
    this.childObjects = ko.observableArray([ new ChildModel(true, false) ]);
};

var viewModel = new ParentModel ();
ko.applyBindings(viewModel);
Run Code Online (Sandbox Code Playgroud)

fyr*_*fyr 4

请尝试以下操作:

this.yearRound.subscribe(function (val) {
        alert('value change');
    });
Run Code Online (Sandbox Code Playgroud)

如果您想让订阅者在加载页面时也被调用,请执行以下操作:

var ChildModel= function (yearRound, fromNow, startDate, endDate) {
    var self = this;

    this.yearRound = ko.observable();
    this.fromNow = ko.observable(fromNow);
    this.startDate = ko.observable(startDate);
    this.endDate = ko.observable(endDate);

    this.yearRound.subscribe(function (val) {
        alert('value change');
    });
    this.yearRound(yearRound);
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/azQxx/1/ - 这对我来说适用于 Chrome 16 和 Firefox 10

每次选中的按钮更改其值时都会触发回调。

observableArray在我看来,如果您可能有多个子模型与父模型关联,那么这很好。