简体   繁体   中英

Caching selectors in objects using jQuery

I was writing a bit of simple UI stuff today and am only able to use jQuery for the project, no Backbone, KnockoutJS, etc...

So, basically I wrote some objects that look like this-ish...

var UI = UI || {};
UI.login = (function($){
    function Welcome(){
        this.firstName = $("#firstName");
        this.lastName = $("#lastName");
        this.email = $("#email");
        this.password = $("#password");

        this.message = $("#message");

        this.init();
    }

    Welcome.prototype.init = function(){
        this.email.bind('blur', $.proxy(this.checkEmail, this));
        // etc..etc...
    };

    Welcome.prototype.checkEmail = function(event){
        var email = $(event.currentTarget).val();    

        if(!checkEmail(email)){
            this.message.html('This email is invalid.')
                .show();
        }
    };

    function checkEmail(email){
        // do dome validation
        return isValid;
    }
    // etc.. etc...

    return Welcome;
}(jQuery))

My question is... Is caching those selectors in the Welcome constructor a GOOD or BAD idea? Also, I'd like to maybe just get some feedback on this pattern...

Thanks!

It's fine if you are reusing those throughout your program. I've done that numerous times before. The pro is that you don't have to regrab those selectors over saving you some execution time; however, it is better to chain methods in jQuery (or so I've read... it's not that big of a difference IMO and you should always optimize for performance when last if it means sacrificing code quality). Part of this is because you're taking a hit by creating these jQuery objects that you may or may not use.

One thing also to note is you will get a bit of performance increase by using local variables, but generally saving these jQuery objects that you would use would be better than the non-local variable hit.

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