Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a single page app with knockout.js?

How do you organize the view-model classes? Separate classes or one giant one (and how to modularize the giant one)? How to switch between 'pages' (with data loaded with ajax of course)? How to load templates for backbonejs after page load? Examples and tutorials would be appreciated as long as they are more advanced that he ones on their site.

like image 896
sdfadfaasd Avatar asked Jan 07 '12 00:01

sdfadfaasd


1 Answers

Wow, lots of questions all rolled into one. I'll try to hit them here, but a disclaimer that I am writing an entire course for Pluralsight on Knockout ... so i can't go into the depth you need an a comment box :)

1) How do you organize model-view classes?

I think you mean view-model classes. I recommend creating a view model that contains all of the properties and methods that the page requires. Put the view model in an enclosure and keep all of that javascript in its own file. For example, if you have page customers.html for your structure, you could have customers.js for with your view model.

2) Separate classes or one giant one (and how to modularize the giant one)?

Each view model is in its own file. Generally 1 view model per js file (but you could certainly put interrelated ones int he same file). Also, generally 1 view model per view (but again, you can go beyond this in some cases).

For Models you can create them all in a single models file if you like, or put them in separate files. For smaller apps I like 1 models.js files since most models are pretty straight forward, small, and contain simple properties (albeit observables). But here, it really is a matter of choice.

3) How to switch between pages?

The mechanism is not specific to Knockout, so you can use links or even custom controls (menus, tabs, etc). Your call. Once you decide how to navigate to a different page, I assume you need to pass data between the 2 for context One way to do this is in the querystring with an ID, another way is local storage (for larger items you need to store in the client), or there are other options too. Again, it really depends on what you need to pass between the pages. A lot of times I design the pages to be self sufficient so I dont need to pass much between them. For what I need to pass, i try to send as little as I can and look up data based on keys (in ajax calls or local storage ... wherever the data lives).

I hope this helps a bit.

UPDATE: Here is the link I mentioned to my Knockout.js course on Pluralsight

like image 70
John Papa Avatar answered Oct 17 '22 06:10

John Papa