正在触发Knockout JS中子属性的订阅事件

Triggering subscribe event for children properties in Knockout JS

本文关键字:属性 事件 Knockout JS      更新时间:2023-09-26

我在Knockout中触发订阅事件时遇到一些问题。我有一组Schemas,每个Schemas包含若干天。我想在一天的时间戳发生变化时触发我的订阅事件,而不仅仅是在Schema数组发生变化时。

到目前为止,这是我的代码。当从Schemas数组中添加或删除Schema时,底部的订阅事件会触发。但当任何子属性发生更改时,则不会。

{"schemas":[
    {"days":[
        {"from":"12:00","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        ...
    ]},
    {"days":[
        {"from":"06:30","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        ...
    ]}
]} 
var Schema = function(data, parent, index) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
};
var SchemaViewModelMapping = new (function() {
    var self = this;
    self.index = 0;
    self.schemas = {
        create: function(options) {
            self.index++;
            return new Schema(options.data, options.parent, self.index);
        }
    };
    self.index = 0;
})();

var SchemaViewModel = function() {
    ko.mapping.fromJS(data, SchemaViewModelMapping, self);
    self.schemas.subscribe(function(value) {
        **Let me do something when a DAY changes here!!!**
    });
}
var ViewModel = new SchemaViewModel;
ko.applyBindings(ViewModel);

根据@JamesThorpe的建议,我更新了我的代码如下:
我添加了一个新的Day对象,从中添加了我的订阅,我从Schema实例化了它。

{"schemas":[
    {"days":[
        {"from":"12:00","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        ...
    ]},
    {"days":[
        {"from":"06:30","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        {"from":"06:30","to":"17:00"},
        ...
    ]}
]} 
var Day = function(data) {
    var self = this;
    self.from = ko.observable(data.from);
    self.to = ko.observable(data.to);
    self.from.subscribe(function() {
        **Doing my subscribe magic...**
    });
    self.to.subscribe(function() {
        **Doing my subscribe magic...**
    });
};
var Schema = function(data, parent, index) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
    self.days = ko.observableArray();
    data.days.forEach(function(day) {
      self.days.push(new Day(day));
    });
};
var SchemaViewModelMapping = new (function() {
    var self = this;
    self.index = 0;
    self.schemas = {
        create: function(options) {
            self.index++;
            return new Schema(options.data, options.parent, self.index);
        }
    };
    self.index = 0;
})();

var SchemaViewModel = function() {
    ko.mapping.fromJS(data, SchemaViewModelMapping, self);
    self.schemas.subscribe(function(value) {
        **Let me do something when a DAY changes here!!!**
    });
}
var ViewModel = new SchemaViewModel;
ko.applyBindings(ViewModel);