I have a very strange behavior in going on KnockoutJS 1.2.1 (Can’t switch to 2 yet, or believe me I would).
Basically, I have an after render set up on a template. In the after render, I need to retrieve data from my viewModel. When I try to get data from it by viewModel.stuff() inside the render function, a strrrange behavior is occurring. It seems to be calling render multiple times or something.
Here is the code…
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();
});
});
Here is the fiddle…
http://jsfiddle.net/jcreamer898/wZ5bD/
Just try commenting out the var stuff = viewModel.stuff() in the render function and observe the difference in the console log when clicking the button.
Appreciate any help here as I know this one’s a little weird!
Bindings are executed inside of a computed observable, so when you call
viewModel.stuff()in your afterRender function you are creating a dependency for each on thestuffobservable.When you add a new item,
afterRenderis getting called after rendering each of the items again.Look at the date here: http://jsfiddle.net/rniemeyer/wZ5bD/4/
I am not sure of the exact thing that you want to accomplish, but if you need to do it in
afterRenderand don’t want a dependency, then you could perform your action in a setTimeout 0. http://jsfiddle.net/rniemeyer/wZ5bD/5/