Friday 14 April 2017

How to boot a multi-page app with Browserify and Gulp

Ok, I'm near to the finish line with my new PHP/JS app built with Gulp and Browserify. The last part is how to "boot", I mean how to do the "first call".

Let's say I have 3 JS entry points

/js/articles.js
/js/categories.js
/js/comments.js

each of them using some JS modules. Then I have 3 HTML files, requiring their JS

/articles.html
/categories.html
/comments.html

example /js/articles.js

var $ =                 require("jquery");
var common =            require("../common.js");

var viewModel = {

    readData: function() {
        /* read record from API and render */
    },

    insert: function() {
        /* open a modal to insert new record */
    }
};

What I should do now is to perform this sort of "boot": that is calling some init function I need, then load server data, then bind all buttons and stuff to viewModel's methods

$(document).ready(function() {
    common.init();
    viewModel.readData();
    $('#btn-add').click(viewModel.insert);
});

Ok, but where am I to put this?

A) In HTML file? I can't cause I don't have any global JS variabile to access..

B) Am I put it into articles.js? At the moment, my Gulp task will bundle everything (articles.js, categories.js, comments.js, common libraries) into a single bundle.js. If I put it into articles.js it will end up into the bundle.js. So articles-related boot stuff would be called in "categories" page either. And this is wrong.

C) Should I split articles.js into 2 files, one containing viewModel definition and the other doing the $(document).ready stuff?... but again how do I access to the correct viewModel?

Which is the correct solution?

Thank you



via user2029958

No comments:

Post a Comment