0

I'm currently using the Laravel PHP MVC Framework to develop a web application; and it's going along quite nicely. I'm very comfortable with the expectations of the framework and how my application should be structured. This is not a problem.

My problem is with the front end, UI/interaction side. I am using Knockout.js & jQuery to encapsulate a lot of front end UI & data interaction; and I'm not sure I'm using the former correctly.

Knockout.js prides itself on binding elements in the DOM to event handlers and functions in a Javascript "ViewModel" layer, allowing you to send requests away to the server via AJAX to fetch new data, add templates of HTML to your current DOM, and alter what is present on your page. I understand this within a single page context. By that, I mean, if I have a discrete page where I need user & data interaction, I will probably end up creating a SomeSinglePageViewModel.js file to handle this.

What I am not to sure about is how, or even whether, Knockout.js view models should be used across/between pages. Right now, I'm creating a ViewModel for nearly every CRUD operation and page in my application. Is this correct design?

For example, I'll have a CreateUserViewModel.js for my /User/Signup page, and a EditUserViewModel.js for my /User/Edit page; and a `HomePageViewModel.js for the application landing page to control that UI. Is it correct to follow a "one viewmodel per page" philosophy? Or am I doing it wrong? Is it meant to be a "one viewmodel per data model" philosophy?

Where do I draw the line between ViewModels? Do I risk encapsulating too much functionality into one object, or do I risk separating everything out too broadly and creating duplicative files? How have you structured your Knockout.js ViewModels?

1

Very purpose of ViewModel is to covert and display the data in your model to match the view. Simply creating a ViewModel per view would be the best way to handle this.

0

As mentioned by Pelican, you are taking the right approach in terms of tailoring your viewmodels to your views. That said, you can still abstract some functionality out for reuse. For example, you might have use for paging lists in multiple views. In that case, create a generic model that can be reused in multiple viewmodels.

If you find you require more completely functionality, like passing state, dealing with complex CRUD operations etc, then Knockout is probably not best for those cases. In that case, BackBone.js (or fuller frameworks like Angular etc) are more suited to that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.