【发布时间】:2018-04-07 05:25:47
【问题描述】:
我在我的View 中使用KnockoutJS 到data-bind 的一些元素:
<div>
<h2 data-bind="text: wTitle"></h1>
<div data-bind="text: wSynopsis"></div>
</div>
在我的ViewModel 中,我有控制这些元素的observables。他们根据对 Wikipedia 的 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]);
};
}
我的Model 在下面(为简单起见,删除了所有不相关的代码):
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。
【问题讨论】:
标签: javascript html mvvm knockout.js observable