Friday, November 14, 2014

Refresh/Update jQuery Selector after Ajax or other DOM Manipulation

jQuery Logo

I'm working on a more or less single page app right now. As such, there's a lot of dynamic DOM manipulation. Sometimes, we need to re-evaluate a jQuery selector to get the new set of objects after the DOM has changed.

Typically we've solved this problem by always using the selector to find the children. This became really frustrating in my Jasmine tests where I found myself doing this a lot!

    it("toggles the display of an element", function() {
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).toBe(0);
        
        $button.trigger('click');  
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).not.toBe(0);
        
        $button.trigger('click');  
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).toBe(0);
    });

Even in production code (outside of tests) that can be kind of a pain. I wanted to be able to do something more like this:

    it("toggles the display of an element", function() {
        var $togglableItem = $('.togglable');
        expect($togglableItem.length).toBe(0);
        
        $button.trigger('click');  
        expect($togglableItem.refresh().length).not.toBe(0);
        
        $button.trigger('click');  
        expect($togglableItem.refresh().length).toBe(0);
    });

A Common Solution

I've seen some implementations of a jQuery refresh plugin that look like this:

(function($) {
    $.fn.extend({
        refresh: function() { return $(this.selector); }
    });
})(jQuery);

I have two problems with this approach. First, I don't always have my elements attached to the DOM when I want to do a refresh. In fact, typically in testing, I don't add my test elements to the DOM so I can't just reuse the selector. The selection depends on the parent jQuery object.

Second, I also really enjoy the fluency of jQuery and often make use of .end() method when it makes sense. The approach above flattens the selector stack and .end() returns the default jQuery object.

Preferred Approach

To maintain the fluency of jQuery and allow the refresh, here's what I'm proposing:

(function($) {
    $.fn.extend({
        refresh: function() { 
            var $parent = this.end();
            var selector = this.selector.substring($parent.selector.length).trim();
            return $parent.find(selector); 
        }
    });
})(jQuery);

Caveats

I haven't used this in the wild yet. I know .selector is deprecated, but it's the best I could find for now. It does, however, work pretty darned well in my Jasmine tests. :)

19 comments:

  1. Thanks for sharing your information. Great efforts put it to find it which is really amazing. It is very useful to know, Definitely will share the same to other forums.
    best openstack training in Chennai | openstack training center in Chennai | openstack certification training in Chennai | openstack course fees in chennai

    ReplyDelete
  2. beautiful Article.
    valuable information.
    keep sharing.
    best java training in bangalore

    ReplyDelete
  3. Every good business must have a roadmap that tells exactly how the company is, its potentials and makeup. This important document serves as a guarantee for assistance by any technical or financial institution. It is thus imperative that young entrepreneurs consider developing their own business plan for their enterprises. 출장안마

    ReplyDelete
  4. If you're a business owner, this article will discuss why you should be insuring your company vehicles. Anytime your company vehicle is on the road, it is at risk. buy wise account

    ReplyDelete
  5. Digital Marketing Agency located in Point Pleasant New Jersey. Specializing in Lead Generation, Funnel Building and Website design to attract high quality clients for businesses. seo consulting

    ReplyDelete
  6. Online directories can be quite beneficial for startups and small business firms. Business owners just need to understand how online business directories work. Online directories are site submission services which allow businesses' sites to be added to particular categories where the websites become easy for interested visitors to search. 출장안마

    ReplyDelete
  7. The price of games do not come cheap in an unstable economy especially when it is a mega-hit title released from a well-known company. These are some handpicked strategies gamers can use without resorting to starvation or breaking bank accounts. 홀덤사이트

    ReplyDelete
  8. Technically flash games are interactive games created using the Adobe Flash software. Macromedia originally owned and developed the Flash software for use in animation programming and was being used to create movies and TV shows and complex business presentations. Soon after, Flash was picked up by programmers to create web-based interactive games. pggame365

    ReplyDelete
  9. Are you thinking about starting a business in 2020, but don't know how or even where to begin? This article outlines the biggest obstacles to overcome, what you need to start your business, and what to do after year one! bookkeeping and accounting

    ReplyDelete
  10. Every good business must have a roadmap that tells exactly how the company is, its potentials and makeup. This important document serves as a guarantee for assistance by any technical or financial institution. It is thus imperative that young entrepreneurs consider developing their own business plan for their enterprises. acim

    ReplyDelete
  11. Starting an online business regardless of what type it is, can really be a daunting process. With hundreds of businesses cramming the internet on a daily basis and with the millions already there, I have to ask the question, Do I have a chance of success in whatever niche my business falls into? There are times when some of us have come to the end of the road for our 9am to 5pm jobs, and we think it's time to take on the challenge of being our own boss and manage our own business. However, there are a number of things to take into consideration when thinking about starting your own business. I will only focus on ten main things from a long list which, in my opinion, are of paramount importance when considering an online business. acim soundcloud

    ReplyDelete
  12. A laser engraving business is a very profitable business one can start from home. For someone thinking of pulling out of formal employment, laser engraving offers a great opportunity to venture into business. But is it right for you? quantum forgiveness

    ReplyDelete
  13. Every good business must have a roadmap that tells exactly how the company is, its potentials and makeup. This important document serves as a guarantee for assistance by any technical or financial institution. It is thus imperative that young entrepreneurs consider developing their own business plan for their enterprises. texas license to carry a handgun

    ReplyDelete
  14. Every good business must have a roadmap that tells exactly how the company is, its potentials and makeup. This important document serves as a guarantee for assistance by any technical or financial institution. It is thus imperative that young entrepreneurs consider developing their own business plan for their enterprises. authors a course in miracles

    ReplyDelete
  15. Dergh.com is a social networking website that provides a safe platform for everyone. Our mission is to help people find and share anything from topics to messages. Dergh.com supports public and private messaging, profiles, pictures, search, notification, multimedia, polls and much more. dergh.com

    ReplyDelete
  16. Every good business must have a roadmap that tells exactly how the company is, its potentials and makeup. This important document serves as a guarantee for assistance by any technical or financial institution. It is thus imperative that young entrepreneurs consider developing their own business plan for their enterprises. Noodol media

    ReplyDelete
  17. Business owners contemplating a sale of their business should allocate the proper time and attention into planning this event. Not every business listed for sale is actually sold. There are a number of reasons why and it would be advised that small business owners recognize these challenges and take the necessary steps to address them. cheapest home loan

    ReplyDelete
  18. It seems like everyone is jumping on the designer bandwagon these days. And why not? The fashion industry is sexy - fashion shows, parties, celebrities, recognition, and even fame go along with a career in fashion. scar camouflage

    ReplyDelete