ko.subscribe儿童模型属性

时间:2012-02-08 22:03:03

标签: 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>
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);

1 个答案:

答案 0 :(得分:4)

尝试使用以下内容:

this.yearRound.subscribe(function (val) {
        alert('value change');
    });

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

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);
}

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

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

如果您可能有多个与父母关联的子模型,observableArray我认为没问题。