开发者

Knockout JS - MVVM pattern, where does my ui logic go?

This sounds like a stupid question, but thought I would post anyway...

I am just making a simple web app with javascript and html and decided upon Knockout JS for the main framework to manage the UIs. However I am a bit puzzled how to proceed.

My first page is a very simple login page, it just has a username and pa开发者_C百科ssword box, the problem comes when I want to do thing with the UI. An example would be adding a watermark to the ui boxes, or adding logic around listening to custom events, I could just write it as in-line javascript but I cannot really unit test any of it then.

Originally I was planning to use an MVC style pattern so I could unit test the controller with a mocked view, and just put any ui logic in there.

So is there any acceptable way of doing this without putting it all as in-page logic?


The way mvvm works is that the view should pretty much be a visual representation of that view model, so put your logic in there. If you design it right so your functionality is contained in seperate classes then you can mock them all out easy enough. If you are used to MVC then just see the viewmodel as your controller.

I can see where you are going with your question though, as with complex views you could end up with quite a lot happening within your ViewModel class, but if you just stick to simple oo and encapsulation principles you wont go too far wrong...

So anyway to summarise, put it in your logic in the view model.


There are two approaches you can use. There is an xUnit package for JavaScript called JsUnit So it is possible to unit test your JavaScript-based UI logic. The other route as you mentioned is to use the controller to contain the logic and the JavaScript as a "pure" view model. I personally feel that either approach is viable. You just want to make sure that your JavaScript-based view model doesn't become too intimate with the view. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜