DEV Community

loading...

Reducing spaghetti code on jquery application using model idea

luciunknown profile image Luciano Cardoso Updated on ・2 min read

Using jquery can be tricky sometimes, usually when code don't follow any concern separation. These cases are often related to a poor comprehension of javascript promises and callbacks.And is not rare to see a script file with tons of ajax calls passing the same parameters changing only the url.

As a possible workaround I would suggest making separated classes that holds ajax calls using M from MVC frameworks, js models.

So lets start by encapsulating the ajax calls. I end up with this script, but you can change for something that works for you.

class Api {
   static request(url, promise, formData, method) {
    if (promise)
      return $.ajax({
        url: url,
        dataType: 'json',
        method: method,
        data: formData
      })
    else
      $.ajax({
        url: url,
        dataType: 'json',
        method: 'POST',
        data: formData
      })
    }
}

Next, lets do some template to render ours items.

var PostTemplates = {
    listItem:'<li><span>%(id)i</span><pre>%(title)s</pre></li>'
}

Using a model idea lets create a class that centralize ajax calls related to that object

class Post {
    constructor(postInfo) {
        this.id = postInfo.id;
        this.title = postInfo.title;
    }

    static getList(){
        const url = 'https://jsonplaceholder.typicode.com/posts';
        let request = Api.request(url, true, {}, 'GET');
        return $.when(request); 
    }

    insert(){
         //...
    }

    remove(){
       //...
    }

    render(item){
        return sprintf(PostTemplates.listItem, this)
    }
}

And for last lets use the model by calling getList function

Post.getList().then(function(posts){
    let rootElement = $("#banner-message");
    rootElement.empty();
    $.each(posts, function(index, postInfo){
         rootElement.append(new Post(postInfo).render());
    })
})

My last post was mentioning pure JS and now jquery. That is because I am slowing down to dive into a new js framework. I believe that SPA applications has it's use cases but I would not say that is the best approach for every project out there.

Discussion

pic
Editor guide