dmathisen
dmathisen

Reputation: 2342

Issue with passing data to an observable in KnockoutJS

I'm setting up a template system in my knockout project and the goal is to be able to call the function loadTemplate("templateName") at any time to load a new template into a view.

I have a version of it working in which I can call loadHomeTemplate() or loadSearchTemplate() and it'll work.

JS Fiddle link.

But now I'm trying to modify it so that I can call loadTemplate("Home") or loadTemplate("Search").

JS Fiddle link.

For some reason the 2nd version breaks on this.name = ko.observable(name);. this.name is undefined - I've added console logs to see the error. I don't get it. It seems like I'm passing the same thing to buildTemplate's 'name' parameter in both cases. No?

A couple notes: I'm binding to the 'template-content' element like that because I'm running multiple view models. And I'm declaring loadTemplate or loadHomeTemplate as globals because I need to be able to run the methods any time. There's probably a better way to do it, but I haven't figured that out yet.

Upvotes: 1

Views: 59

Answers (1)

Rango
Rango

Reputation: 3907

The main problem was that buildTemplate must be used with new since it initializes itself as holder of selected template. This fix resolves improper access to name.

self.currentTemplate(new buildTemplate(name, templateData));

In my fork I've also created templateFactory object that holds inside constructors for all specific templates. It makes searching of proper constructor easy and confident.

http://jsfiddle.net/AvYY4/1/

Upvotes: 1

Related Questions