我正在使用 KnockoutJS
对 View
中的一些元素进行数据绑定(bind)
:
<div>
<h2 data-bind="text: wTitle"></h1>
<div data-bind="text: wSynopsis"></div>
</div>
在我的 ViewModel
中,我有控制这些元素的 observables
。他们根据对维基百科的 AJAX
调用来更改元素的内容。
下面是我的ViewModel
(我删除了所有不相关的代码):
var ViewModel = function() {
self = this;
this.wTitle = ko.observable('');
this.wSynopsis = ko.observable('');
this.wikiInfo = function(i) {
var wikiURL = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' + i + '&format=json&callback=wikiCallback';
$.ajax({
url: wikiURL,
dataType: 'jsonp',
success: function(response) {
return new parseAjax(response);
}
})
.fail(function() {
return "Error: Cannot load Wikipedia data!";
});
}
this.wikiInfo(Model.currentMarker);
var parseAjax = function(response) {
self.wTitle(response[0]);
self.wSynopsis(response[2]);
};
}
我的模型
如下(为简单起见,删除了任何不相关的代码):
var Model = {
currentMarker: 0
};
现在,我想访问该 observables
并从我的 ViewModel
外部更改它们的值(即我的 init()
,它位于外部ViewModel
)。
var init = function() {
Model.currentMarker = marker;
ko.applyBindings(new ViewModel());
}
一种方法是更改已经在ViewModel
之外的Model.CurrentMarker
,并通知ViewModel.wikiInfo(Model.CurrentMarker)
更改,因此它会自动刷新 View
,但我认为我只能 subscribe()
到 ViewModel
内的可观察对象,而且我不不知道如何应用:
var init = function() {
ViewModel.wikiInfo.subscribe(function(newValue) {
Model.currentMarker = newValue;
}); // Not working
ko.applyBindings(new ViewModel());
}
另一种方法是更改Model.CurrentMarker
,并调用ViewModel.wikiInfo(Model.CurrentMarker)
。
我无法执行此操作,因为我无权访问 ViewModel
。
var init = function() {
Model.currentMarker = marker;
ViewModel.wikiInfo(Model.CurrentMarker); // ViewModel is not created yet
ko.applyBindings(new ViewModel());
}
注释:
由于其他代码要求:
- 我无法在
init()
开头创建ViewModel
。 - 我需要在
ViewModel
之外使用init()
,我不能将它放在我的内部ViewModel
。
最佳答案
这行得通吗?创建对 ViewModel
实例的引用。
var init = function() {
Model.currentMarker = marker;
var vm = new ViewModel();
ko.applyBindings(vm);
vm.wikiInfo(Model.CurrentMarker);
}
关于javascript - 如何在 KnockoutJS 中访问 ViewModel 之外的可观察对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46943988/