mercredi 17 mai 2017

Javascript code organization data driven application

I'm currently working on the front-end of a medium/large-scale data-driven Asp.net MVC application and I have some doubts about the right code-organization/design pattern to follow. The web application is made by multiple pages containing many Kendo UI MVC widgets defined with razor template.

For those who are unfamiliar with Kendo, the razor syntax is translated to jquery plugin as follow: Kendo server side-wrappers

I defined inside my Script folder two main folders, and i structured my js files as follow:

  • shared //Contains the shared js files -file1.js -file2.js

  • pages //One file per page

    • page1.js
    • page2.js
    • ...
    • Ticket.js // page 4 :)

Each js file is a separate module defined with the following pattern:
Note: Inside init function is registered every callback function to the window events and occasionally a $(document).ready(function(){}) block.

;(function () {
    "use strict";

    function Ticket(settings) {
        this.currentPageUrls = settings.currentPageUrls;
        this.currentPageMessages = settings.currentPageMessages;
        this.currentPageEnums = settings.currentPageEnums;
        this.currentPageParameters = settings.currentPageParameters;         


        this.gridManager = new window.gridManager(); //usage of shared modules

        this.init();
    }

    Ticket.prototype.init = function () {           

            $("form").on("submit", function () {
                $(".window-content-sandbox").addClass("k-loading");
            });

            ...
    }    

    Ticket.prototype.onRequestStart = function (e) {

        ...
    }

    //private functions definition
    function private(a, b, c){

    }

    window.Ticket = Ticket;
}());   

Once i need my javascript functions defined in a module I include the associated javascript file in the page. An istance of my object is stored inside a variable and, on top of that, a function is bound to the widget event (see: onRequestStart).

HTML/JAVASCRIPT

@(Html.Kendo().DropDownList()
      .Name("Users")
      .DataValueField("Id")
      .DataTextField("Username")
      .DataSource(d => d.Read(r => r.Action("UsersAsJson", "User"))
                        .Events(e => e.RequestStart("onRequestStart"))))



var settings = {};

var ticket = new window.Ticket(settings);

function onRequestStart(e){
    ticket.onRequestStart(e);
}

I feel like my design pattern might be unfriendly to other front-end delevoper as I am, mostly because I choose not to implement the javascript modules within Jquery plugin.

First, Am I doing everything the wrong way?
Second, is my design pattern suitable for a Javascript test-framework?
Third, which are the must-have scenarios for Jquery plugins?

Aucun commentaire:

Enregistrer un commentaire