【问题标题】:Can't populate data with binding无法使用绑定填充数据
【发布时间】:2014-10-10 10:27:34
【问题描述】:
这是我第一次尝试使用 HTML5 制作单页应用程序。我正在使用 jquery、knockout 和 sammy。
代码:http://codepaste.net/apdrme
问题是我不知道自己做错了什么。我知道是这样的:
this.get("#/", function() {
this.personList(this.persons);
});
但我还能如何填充列表?
【问题讨论】:
标签:
html
knockout.js
sammy.js
【解决方案1】:
您可以按如下方式填充您的列表:
function ViewModel() {
this.personList = ko.observableArray([{"name":"Josh"}, {"name":"Barry"}, {"name":"Mike"}]);
};
[...]
ko.applyBindings(new ViewModel());
注意在声明时使用ko.observableArray()。因此,您还可以删除参数并在您的主要 Sammy 路由中调用 this.personList([{"name":"Josh"}, {"name":"Barry"}, {"name":"Mike"}]) 并在另一个路由中使用其他值填充列表。
另一个错误是您使用了这里不需要的 with-binding。检查documentation about it。
【解决方案2】:
您通常会使用 jQuery 和 ajax 调用来填充 personList。 personList 应该是一个 ko.observableArray。
this.personList = ko.observableArray();
this.get("#/", function() {
$.ajax({url:"/api/persons/", dataType: 'json', success:function(persons){
this.personList(persons);
}});
});