简体   繁体   中英

Whats the best way to load Object Oriented JS properties dependent on page?

I have and external JS scripts file with all my objects in that runs once the document is ready something like this...

jQuery(function($) {
    var Main = {
        run: function () {
             myFunction.setup();
        }
    }

    var myFunction = {
        setup: function() {
            //Do some stuff here
        } 
    }

    Main.run();
});

I want to be able to run myFunction.setup() only if im on a certain page though otherwise I get errors if that method is looking for elements on the page that don't exist eg a slideshow, menus etc.

At the moment I have got round this by checking if the element exists with .length and if it does then running the rest of the method but I was wondering if there was a nicer way? Maybe like if it was possible to send variables to the scripts file when it loads based on the page im on so it knows what to methods run?

Any help would be really appreciated.

Thanks

Giles

Paul Irish has a great way of doing exactly this, using ID and classes from the body tag to execute certain blocks of code:

http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/

This kind of thing might help:

Page specific

var page_config = {
    setup_allowed: true
    // ... more config
};

Generic

var Main,
    myFunction;

(function ($, _config) {
    myFunction = (function () {
        var _public = {};
        if (_config.setup_allowed === true) {
            _public.setup = function () {

            };
        }
        return _public;
    })();

    Main = (function () {
        var _public = {};
        if (typeof myFunction.setup !== "undefined") {
            _public.run = function () {
                myFunction.setup();
            };
            // Run it as we had Main.run() before
            _public.run();
        }
        return _public;
    })();

})(jQuery, page_config);

This way Main.run() and myFunction.setup() are only available if specified in page_config .

Here's a working example you can have a play with. This may be a bit verbose for your particular requirement but hopefully it'll help in some way :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM