Jump to content

jQuery - heavy custom controls


  • Please log in to reply
No replies to this topic

#1 Guest_ElatedOwl_*

Guest_ElatedOwl_*
  • Guests

Posted 15 February 2013 - 02:37 PM

So I'm writing a custom jQuery control (which isn't anything new for me) and I'm running into an architectural issue - retrieving the value. Anything else I've ever written can just call .val on a standard item (ie some kind of input) however the control I've built should be returning an array of items based off of many checkboxes. I don't have any problems parsing that, however, I'm struggling to determine how I should call it.

The first approach is obvious, just creating another function via $.fn.sortreeVal. It doesn't add a bunch of additional steps to the call stack, can be used via the standard $('blah') selector, but it's going to be available to every single jQuery instance even though it should only be there for my custom control element(s).

My second thought is overriding .val to allow for custom processing. I'd end up having something like
$.fn.rVal = $.fn.val;
$.fn.val = function(value) {
	var customVal = this.data('customVal');
	if(typeof this.data('customVal') === 'function')
	{
		customVal.call(this, value);
	}
	else
	{
		this.rVal.call(this, value);
	}
};
so that when I'm initializing my custom control I can define a custom value getter/setter. This probably seems like the most intuitive way of doing it, however, I hate overriding things that the page doesn't own - if for whatever reason there was a bug another dev that isn't aware of this override I'd imagine he/she would be pretty pissed off when they found it. (I would be, anyway) It also forces a function pointer in memory for every instance of the control and adds an extra function call. (not including what .data is going to call)

One of the common approaches I see is using object instantiation - I'd simply return a new instance of an object that houses all the functions/properties for that control on the $('blah').sortTree call. This gives you a lot of control and re-usability but you're forced to store the object in memory if you want access to it later (usually in the global space, at that) which is pretty balls.

jQuery UI (and I'm sure a lot of others) use an approach of $('blah').control(options) and do all of their work through that - for example, retrieving a value would be like $('#tree').sortTree('value'). It doesn't force you to cache things you don't want to, it keeps the functions limited to that control but it makes writing controls a pain in the ass. (every control would need to follow the same kind of structure and it is a pain in the ass with a lot of boilerplate to set up)



Any thoughts/opinions on this? I'm learning towards overriding val but I feel really guilty doing so.