简体   繁体   English

使用jQuery缓存对象中的选择器

[英]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... 我今天正在写一些简单的UI东西,并且只能在项目中使用jQuery,没有Backbone,KnockoutJS等。

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? 我的问题是...将这些选择器缓存在Welcome构造器中是好还是坏的主意? 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). 但是, 最好在jQuery中链接方法 (或者,我已经读过……IMO的区别不大,如果要牺牲代码质量,那么您应该始终在性能上进行最后优化)。 Part of this is because you're taking a hit by creating these jQuery objects that you may or may not use. 这部分是因为您通过创建可能使用或可能不使用的jQuery对象而受到欢迎。

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. 还需要注意的一件事是,使用局部变量可以使性能有所提高,但是通常保存要使用的这些jQuery对象要比非局部变量命中更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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