我有2个变量声明为mtn和atn,其值根据API ajax响应填充。
现在,我正在使用API响应返回的值分配mtn和atn变量,在我的情况下,因为mtn将为null,而atn具有10位数字。所以我使用atn的子字符串分配atn1,atn2,atn3,而mtn1,mtn2和mtn3不受影响,如下面的代码片段所示。
var ViewModel = {
mtn: null,
atn: null,
mtn1: ko.observable(null),
mtn2: ko.observable(null),
mtn3: ko.observable(null),
atn1: ko.observable(null),
atn2: ko.observable(null),
atn3: ko.observable(null)
}
// Ajax API call happens and assigns ViewModel.mtn and ViewModel.atn
if (ViewModel.mtn != null && ViewModel.mtn.length == 10) { //This condition is not true because ViewModel.mtn is coming as null in case and so mtn1, mtn2 and mtn3 observables are untouched
ViewModel.mtn1 = ViewModel.mtn.substring(0, 3);
ViewModel.mtn2 = ViewModel.mtn.substring(3, 6);
ViewModel.mtn3 = ViewModel.mtn.substring(6, 10);
}
if (ViewModel.atn != null && ViewModel.atn.length == 10) {
ViewModel.atn1 = ViewModel.atn.substring(0, 3);
ViewModel.atn2 = ViewModel.atn.substring(3, 6);
ViewModel.atn3 = ViewModel.atn.substring(6, 10);
}
ko.applyBindings(ViewModel);
// Click event happens from View and Business logic UI validations take place below
processClick: function() {
.var strmtn = ViewModel.mtn1 + ViewModel.mtn2 + ViewModel.mtn3; // This is not working and throwing error and only ViewModel.mtn1() is working
var stratn = ViewModel.atn1 + ViewModel.atn2 + ViewModel.atn3; // This is working fine but ViewModel.atn1() is not working.
我认为访问atn1作为ViewModel.atn1的方法正在工作,而访问mtn1作为ViewModel.mtn1的方法不起作用是因为为atn1重新分配了observable,而没有触及mtn1。
那么我怎么知道调用可观察值的访问方法,因为我不知道我的可观察量是否被触及了? :(
P.S:我正在使用的Knockout 3.x版本中出现此问题。我刚刚添加了2.x版本。
答案 0 :(得分:1)
observable是一个getter-setter函数。要设置其内容,请执行
ViewModel.mtn1(ViewModel.mtn.substring(0, 3));
要获取其内容,请执行
value = ViewModel.mtn1();