ko.subscribe子模型属性



寻找如何在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 subscribennwhy 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);

尝试以下操作:

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就可以了。

相关内容

  • 没有找到相关文章

最新更新