Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery widget development - can I use an MVC pattern?

I have been using knockoutjs and backbone to create a single page JavaScript application. I use backbone models and knockout view models, but I also have a lot of UI controls which I've used the jQuery UI widget factory to create.

My question is how to better structure the code in my jQuery widgets. Frameworks like knockout/backbone/ember make it easy to implement an MVC type pattern in the main app, but when it comes to widget development I end up having a big mush of code which output and manipulates DOM elements. I can still test this because jquery makes it easy to query the DOM but the code is pretty ugly. Ideally I'd like to have an MVC pattern in my widgets also.

Are there any libraries or frameworks out there designed to help out with this?

like image 813
Charlie Avatar asked Apr 17 '12 14:04

Charlie


1 Answers

In short:

  • Keep widgets as much as a view part of the MVC as you can. Delegate the data out whenever possible.
  • Don't write your widget with the predisposition of it being in your app. Treat the widget like a an island.
  • Use Events to handle data passing out of the widget. Don't query for it.
  • Use "Tell, Don't ask" pattern in widgets to keep the controller clean

Ideally, JQuery is the V part of the MVC pattern of your overall application. If widgets you have need to retain and return data when the user interacts with them, eventing is the way to go. Use the "Tell, don't ask" pattern of development in your widgets so that you don't have to query the state of your widgets to do something. This should clean up many of the issues.

like image 121
Brandon Avatar answered Oct 20 '22 07:10

Brandon