-2

I have a task, where I need to render the inner page of a blog via JavaScript.

The page has infinite scroll feature.

On initial page load, I get all the data for the initial post via JSON string right in the HTML, then I render it with JavaScript.

For the next pages(for the infinite scroll) I need to make a call to an API, which then returns me the same JSON string for the next post.

My question is - how or even should I use MVC for this? I'm fairly new to the concept, still trying to jump on the right tracks.

I'm thinking bout the following setup now.

data.js - an object where I will store all the data that I get from JSON string, and it will have update(APIJSON) method to update itself from the API when I do a call.

template.js - just template literals - takes in date, returns HTML.

view.js - takes data.js as this.data in constructor, then has render method which takes the HTML that template returns and just puts it in content via innerHTML.

model.js - getPost() method does a call to api, returns data.

controller.js - This is the part where I'm not sure what to do here. Should controller listen to on scroll event, and if I reached the end of page it should then tell model to do getPost() and then view to do render()? How do I transfer the data I get from model's getPost() into my views render()? I can't seem to be able to call view from inside of XHR request?

Did I miss something? OR maybe my whole concept of how MVC works is false? All I need is someone to get me on the right track, I'll do the rest myself. Really loving JavaScript, started learning only few months back.

1 Answers1

1

The controller.js file can host a method that will trigger the data fetch from the model and (returns it to the view | updates the data.js and triggers an observer to render it) when the Promise/Ajax call resolves.

But there is no need to be super strict on such a small project. Just use the structure that is the easiest to maintain for you in the future and makes sense to you.

b-m-f
  • 1,278
  • 2
  • 13
  • 29
  • Thank You for explaining the flow to me, Bananenmannfrau! I want to use MV* here so I could learn it in a practical way. Perhaps You could give me a little example of what an observer and controller would look like in a project like this? Seems that I skipped something somewhere in my theory of how it all works. Pretty much - controller.js would have a method, say loadArticle() = which would have something like this.model.getPost() right? How do I call this method correctly on scroll? And then when getPost() requests is finished, how exactly do I tell view to render the data it gets? – Karolis Stakėnas Jul 17 '17 at 08:56
  • 1
    Check out these links: https://en.wikipedia.org/wiki/Observer_pattern https://stackoverflow.com/questions/15861344/node-js-how-to-make-a-simple-live-page-update Just try to play around with it. That is the best way to make it click. Reading always only get you so far :) – b-m-f Jul 17 '17 at 11:17