Note that there are some explanatory texts on larger screens.

plurals
  1. POEncapsulating UI components with jQuery
    text
    copied!<p>I'm building an app that involves creating several unique UI "widgets", and I'm having trouble figuring out a good practice for encapsulating the logic behind these UI components with jQuery. These are <em>mostly</em> one-off components that aren't reused several places in the app.</p> <p>I've been experimenting with the <a href="http://github.com/danwrong/low-pro-for-jquery" rel="nofollow noreferrer">lowpro plugin</a>, and while it does allow more or less what I want, I feel like I'm going against "the jQuery way" by using it.</p> <p>To provide some context, here's an abbreviated extract of something I wrote using lowpro. It's a sortable list that other elements can be drug into. When it's initialized empty, it shows a placeholder.</p> <pre><code>FieldList = $.klass({ initialize: function() { this.placeholder = $('#get-started-placeholder'); if (this.items().length == 0) { this.deactivateList(); } else { this.activateList(); } }, items: function() { return this.element.children('li:visible'); }, deactivateList: function() { this.element.hide(); this.element.sortable('destroy'); this.placeholder.show(); var instance = this; this.placeholder.droppable({ hoverClass: 'hovered', drop: function(e, ui) { instance.receiveFirstField(ui.helper); } }); }, activateList: function() { this.placeholder.hide(); this.placeholder.droppable('destroy'); this.element.show(); var instance = this; this.element.sortable({ placeholder: 'placeholder', forcePlaceholderSize: false, tolerance: 'pointer', handle: 'h4', opacity: 0.9, zIndex: 90, stop: function(e, ui) { instance.receiveField(ui.item); } }); }, receiveFirstField: function(element) { ... this.activateList(); }, receiveField: function(element) { ... } }); $(function() { $('ol#fields').attach(FieldList); } </code></pre> <p>Notice that I have a bit of state going on here, and some instance methods that I wish I could make private, etc. So, any jQuery pros out there that can tell me how they'd do this without relying on something like lowpro that perhaps contorts Javsacript into something it shouldn't be? I have a feeling there's a clean way to accomplish something like this with the Module Pattern I saw mentioned <a href="https://stackoverflow.com/questions/188663/jquery-javascript-design-self-executing-function-or-object-literal">in this thread</a>, but the pieces aren't really coming together for me.</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload