【发布时间】:2012-02-23 11:40:30
【问题描述】:
我在使用 KnockoutJS 1.2.1 时有一个非常奇怪的行为(还不能切换到 2,或者相信我会的)。
基本上,我在模板上设置了后渲染。在渲染后,我需要从我的 viewModel 中检索数据。当我尝试通过渲染函数中的 viewModel.stuff() 从中获取数据时,会发生 strrrange 行为。好像是多次调用render什么的。
这里是代码...
var viewModel = {
stuff: ko.observableArray([{ id : 1, name : 'Thing'},
{ id: 2, name : 'Thingier' },
{ id : 3, name : 'Thingiest' }])
};
window.render = function(el){
// This line does weird stuff!!
// Observe the console with and without it
// All I want to do is get my stuff...
var stuff = viewModel.stuff();
console.log(el);
};
var update = function(){
console.log(viewModel);
viewModel.stuff.push({ id : 4, name : 'Thingiestest' });
};
$(function(){
ko.applyBindings(viewModel);
$("#add").click(function(){
update();
});
});
这是小提琴……
http://jsfiddle.net/jcreamer898/wZ5bD/
只需尝试在渲染函数中注释掉 var stuff = viewModel.stuff() 并在单击按钮时观察控制台日志中的差异。
感谢任何帮助,因为我知道这有点奇怪!
【问题讨论】: