我在Knockout中触发订阅事件时遇到了一些麻烦。我有一系列架构,每个都有几天。我想在一天的时间戳发生变化时触发我的订阅事件,而不仅仅是当架构数组发生变化时。
到目前为止,这是我的代码。当从Schemas数组中添加或删除Schema时,底部的subscribe事件会触发。但是当任何儿童属性发生变化时都不会。
{"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);
答案 0 :(得分:1)
按照@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);