admin管理员组文章数量:1405570
I have been following the Modular Design Pattern for quite some time now and find it extremely useful as it helps in the well maintenance of code & separation of blocks into modules.
Regular usage of the module structure with jQuery
has led to most of my applications/code following the below structure:
(function() {
var chat = {
websocket: new WebSocket("ws://echo.websocket/"),
that: this,
init: function() {
this.scrollToBottom();
this.bindEvents();
this.webSocketHandlers();
},
bindEvents: function() {
this.toggleChat();
this.filterPeople();
thispose();
},
elements: {
indicator: $(".indicator"),
statusText: $(".status-text"),
chatHeadNames: $(".people li .name"),
filterInput: $("#filter-input"),
msgInput: $("#msg-input"),
sendBtn: $(".send")
},
...
...
...
filterPeople: function() {
var that = this;
this.elements.chatHeadNames.each(function() {
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
},
...
...
};
chat.init();
})();
What I would like to know is whether referencing all my elements via jQuery
as part of a single variable chat.elements
is a good practice?
One part of me tells that it indeed is a good way to reference all your selectors at once and cache them in variables so that multiple usages of the same element can be done with the cached variables (instead of multiple DOM selections).
Another part of me tells that this might be an anti-pattern and specific elements should be selected and cached locally when required.
I have used similar structures throughout and have got mixed responses about the code, but nothing solid. Any help would be appreciated. Thanks!
I have been following the Modular Design Pattern for quite some time now and find it extremely useful as it helps in the well maintenance of code & separation of blocks into modules.
Regular usage of the module structure with jQuery
has led to most of my applications/code following the below structure:
(function() {
var chat = {
websocket: new WebSocket("ws://echo.websocket/"),
that: this,
init: function() {
this.scrollToBottom();
this.bindEvents();
this.webSocketHandlers();
},
bindEvents: function() {
this.toggleChat();
this.filterPeople();
this.pose();
},
elements: {
indicator: $(".indicator"),
statusText: $(".status-text"),
chatHeadNames: $(".people li .name"),
filterInput: $("#filter-input"),
msgInput: $("#msg-input"),
sendBtn: $(".send")
},
...
...
...
filterPeople: function() {
var that = this;
this.elements.chatHeadNames.each(function() {
$(this).attr('data-search-term', $(this).text().toLowerCase());
});
},
...
...
};
chat.init();
})();
What I would like to know is whether referencing all my elements via jQuery
as part of a single variable chat.elements
is a good practice?
One part of me tells that it indeed is a good way to reference all your selectors at once and cache them in variables so that multiple usages of the same element can be done with the cached variables (instead of multiple DOM selections).
Another part of me tells that this might be an anti-pattern and specific elements should be selected and cached locally when required.
I have used similar structures throughout and have got mixed responses about the code, but nothing solid. Any help would be appreciated. Thanks!
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Feb 27, 2017 at 12:40 nashcheeznashcheez 5,1831 gold badge30 silver badges54 bronze badges 3- using element to select name and status or other things is not good idea whats happend if somebody change the name with inspect element? or tomorrow your teammate changing the theme everything will be broken! – masoud soroush Commented Mar 3, 2017 at 0:39
- keep data in arry or object and for storing use localstorage – masoud soroush Commented Mar 3, 2017 at 0:45
-
The element properties get parsed at page load and events are bound directly to the node, so if somebody changes the name with inspect element, it won't cause an issue. And
localstorage
is a bad idea for this. – nashcheez Commented Mar 3, 2017 at 10:05
2 Answers
Reset to default 6 +50Caching the selectors is a good thing. Hanging on to them is a good idea. It improves performance over repeatedly querying the DOM for the same thing. The code you have above looks very similar to BackboneJS and MarionetteJS code.
I do have some warnings for you though:
- This pattern could cause memory leaks. Consider the case where you destory a subview, but you keep a reference to something that selected it. This is called a dangling pointer. The view won't really disappear. All bindings will remain. Events will continue to fire behind the scenes.
- You will eventually run into a bug where you decided to re-render part of your screen. Cleaning up all your bindings is then required and you need to remember to delete and selectors. If you don't do this you will almost certainly run into issues where you wonder why an event is indeed firing but nothing appears to happen on screen.... (this will be because its happening off screen, to the element that you tried to delete, that still exists... sorta).
- The current way you are querying for elements causes searches against the entire page. Take a look at https://api.jquery./find/. If you cache one selector and then perform searches within that selector it may gain you a little performance bump.
- I think, If the chat module has selectors only for its children, then it's a good pattern. Like:
<div id="chat-module">
<div class="indicator">...</div>
<div class="status-text">...<div>
...
</div>
<script src="and your chat module.js"></script>
// your chat module selecting .indicator:
// $('#chat-module.indicator')
- Also, add a shut-down function to your module. So, when you remove it from the view (as in a single-page-app), you can nullify your selectors and detaching event handlers, like:
delete this.elements.indicator
and event detaching code.
There are also other/better patterns for this, like, when a user types something, you fire an event, and catch that event in your module. To separate UI and the code.
本文标签: jqueryUsing modular design pattern in Javascript with DOM selectionsStack Overflow
版权声明:本文标题:jquery - Using modular design pattern in Javascript with DOM selections - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744231506a2596358.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论