gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:55:42 25 4
gpt4 key购买 nike

我在 Knockout 中触发订阅事件时遇到一些问题。我有一系列模式,每个模式都有很多天。我想在一天的时间戳发生变化时触发我的订阅事件,而不仅仅是在架构数组发生变化时触发。

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

{"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 对象,从其中添加我的订阅,我从架构中实例化该对象。

{"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);

关于javascript - 在 Knockout JS 中触发子属性的订阅事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26252049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com