0

Using this Difference between jQuery.extend and jQuery.fn.extend? Is there a way to have something like $('.selector').Group.Method(); and $('.selector').Group.Method2();

Right now I have a this in a main script

function Forty() {};

var Forty = new Forty();

(function(site) {
    $.extend(Forty, {
        getBaseUrl: function(extra) {
            extra = typeof extra !== 'undefined' ? extra : '';
            return Forty.get('baseUrl') + extra;
        },
        get: function($what) {
            return site[$what];
        }
    });
})(site);

Then later in that file I have:

$.extend(Forty, {
    flyOut: function() {
        $(this).on('click', function() {
            $('html').toggleClass('nav-open');
        });
    }
});

And at the very end I have:

$.fn.extend({Forty: Forty});

Right before I have this line:

$('.selector').Forty.flyOut();

So I'd really like something like $('.selector').Forty.flyOut();

Is something like this possible?

Community
  • 1
  • 1
Marais Rossouw
  • 937
  • 1
  • 10
  • 29
  • Yes, but you'll probably have to refactor your code. The word you need to google is "chaining" wrt jQuery plugins. – Andy Oct 09 '14 at 12:13
  • `var Forty = new Forty();` is a very, very bad idea. – Bergi Oct 10 '14 at 08:53
  • And, **NO**, it's [possible but you shouldn't do it](https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance) – Bergi Oct 10 '14 at 08:54
  • That's the case with Prototype, would this be the same with jQuery? – Marais Rossouw Oct 10 '14 at 23:15

1 Answers1

0

I managed to solve this, by going:

var Forty = {fn:{}};

$.fn.extend({Forty: function() {return $.extend(this, Forty.fn);}});

Then assigning my own functions like so:

Forty.fn.flyOut = function() {
    $(this).on('click', function() {
        $('html').toggleClass('nav-open');
    });

    return this;
}

and using them like:

$('.js-toggle-nav').Forty().flyOut();

This seemed to work epicly!

Marais Rossouw
  • 937
  • 1
  • 10
  • 29