DEV Community

Luciano Cardoso
Luciano Cardoso

Posted on • Updated on

Reducing spaghetti code on jquery application using model idea

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
      })
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, lets do some template to render ours items.

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

Enter fullscreen mode Exit fullscreen mode

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)
    }
}

Enter fullscreen mode Exit fullscreen mode

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());
    })
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)