[jQuery] Proper jQuery object creation for chaining
Sorry in advance if this is confusing...
I am new to jQuery (converting myself from Prototype), and as such I
am finding situations where I need to create a new object, which I
would have done with a class in Prototype (as such, doesn't make sense
for it to appear anywhere except the start of a chain, since it will
return a new object). This object will also be used similar to a
superclass for other objects as well. I also want the object to be
chain-able as well.
My first attempt at this was something along these lines:
(function($) {
function create($opts) {
// some code to create an object
return obj;
}
$.fn.firstObj = function($opts) {
// Error any chained calls
if (this.length) throw SyntaxError();
return create($.extend({}, arguments.callee, $opts));
}
$.extend(
$.fn.firstObj,
{
// Some public methods and default properties
prop1: 'val1',
prop2, 'val2',
method1: function() { dosomething(arguments); }
}
);
})(jQuery);
(function($) {
function create($opts) {
// some code to create an object
return obj;
}
$.fn.secondObj = function($opts) {
// Error any chained calls
if (this.length) throw SyntaxError();
return $.fn.firstObj($.extend({}, arguments.callee, $opts));
}
$.extend(
$.fn.secondObj,
{
// Some public methods and default properties
prop1: 'newval1', //overrides $.fn.firstObj.prop1
newprop2, 'val2',
newmethod1: function() { dosomethingelse(arguments); }
}
);
})(jQuery);
Problem is, that say I chain either of the returned objects, I lose
the public methods for those objects.
example:
var newObj = $.fn.firstObj({prop1: 'foobar'});
console.log(newObj.method1 + ''); // logs: function()
{dosomething(arguments);}
newObj.click( function() { console.log(this.method1 + ''); } ); //
logs undefined now (I've also tried $(this).method1)
What is the proper way of creating a new object in jQuery so that it
can properly be chained afterwards?