淘汰赛JS Ajax调用未填充可观察数组 [英] Knockout JS Ajax call not populating observable array
问题描述
以下示例显示了使用Json填充的可观察数组,然后您可以根据'type'将结果过滤到2个列表中.
The below example shows an observable array being populated from with Json, which then allows you to filter the results into 2 lists based on 'type'.
一切正常,直到我尝试从ajax调用中加载完全相同的Json!
This all works fine until I try and load exactly the same Json from a ajax call!
奇怪的是,如果我在脚本中添加了警报,则可以正常工作...
The strange thing is if i put an alert in the script it then works fine...
<h2>Brand</h2>
<ul id="list-dimensions" data-bind="foreach: filteredDimensions('BRAND')">
<li>
<div class="item">ID</div> <span data-bind="text: $data.id"</span>
</li>
</ul>
<h2>Area</h2>
<ul id="list-dimensions" data-bind="foreach: filteredDimensions('AREA')">
<li>
<div class="item">ID</div> <span data-bind="text: $data.id"</span>
</li>
</ul>
function ProductDimensionsViewModel () {
var self = this;
self.dimensions = ko.observableArray();
var baseUri = 'api/product_dimensions.php';
/*$.getJSON(baseUri, function(data){
success: self.dimensions = data;
});*/
$.ajax({
type: 'GET',
url: baseUri,
data: {},
context: this,
success: function(data) {
self.dimensions = data
},
dataType: 'json'
});
self.filteredDimensions = function(type) {
return $.map(self.dimensions, function(dimension) {
if (dimension.type == type) {
return dimension;
}
});
}
}
ko.applyBindings(new ProductDimensionsViewModel());
推荐答案
您要替换变量,而不是对其进行更新:
You are replacing the variable, not updating it:
...
success: function(data) {
self.dimensions = data
},
...
可观察对象以这种方式更新:
Observables are updated this way:
...
success: function(data) {
self.dimensions(data)
},
...
我不会使用filteredDimensions('AREA')
,因为这会在您的页面呈现后立即被调用.使用可观察变量,将值存储在变量currentFilter
中,然后通过模板加载正确的视图.另外,如果您只有两个过滤器,则更好的方法是使用两个方法:filterByArea
和filterByBrand
.
I wouldn't use filteredDimensions('AREA')
because this gets call as soon as your page is rendered. Use observables, store in a variable currentFilter
the value and then through a template load the proper view. Also, if you only have two filters, a better approach is just to have two methods: filterByArea
and filterByBrand
.
EDIT :添加了示例: http://jsfiddle.net/jjperezaguinaga/spdKE/4/
这篇关于淘汰赛JS Ajax调用未填充可观察数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!