This is a migrated thread and some comments may be shown as answers.

Javascript functions being called multiple times

7 Answers 1051 Views
MVVM
This is a migrated thread and some comments may be shown as answers.
Neeraj
Top achievements
Rank 1
Veteran
Neeraj asked on 23 Sep 2017, 06:50 AM
Hello,
           I have ASP.NET MVC project. There is a view which we have done in kendo MVVM .there are MVVM dropdown, grid, autocomplete.etc. On document.ready() there is alert that have kept. 
          Now when load the MVVM page,  get  when close the window and open again, get 2 alerts .. and it multiplies when close and reopen  view until page refresh from . What is the solution to this?

7 Answers, 1 is accepted

Sort by
0
Veselin Tsvetanov
Telerik team
answered on 26 Sep 2017, 10:02 AM
Hi Neeraj,

It appears, that the event which opens the alert gets attached multiple times, which forces it to be executed multiple times.

Note, that if you need any further assistance on this case, a runnable sample reproducing the issue would be required.

Regards,
Veselin Tsvetanov
Progress Telerik
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Neeraj
Top achievements
Rank 1
Veteran
answered on 03 Oct 2017, 03:40 AM

Here is my code, there are multiple external templates being used :

.cshtml View:

@model Rezcue.ViewModel.AirPNRViewModel
 
<link href="~/Content/PricingWindow.css" rel="stylesheet" />
 
 
 
<form id="PricingForm" data-role="validator" novalidate="novalidate">
    <div id="AirPricingContainer" data-Template="PricingWindowTemplate" data-bind="source:Item">
 
 
    </div>
 
</form>
    <script type="text/javascript" class="AirPricingDivScript">
        var PricingViewModel = null;
        var pricingWindowFormValidator;
        var SelectedFareFamily = null;
 
 
 
 
        $(document).ready(function() {
            debugger;
            
            PricingViewModel = kendo.observable({
                Item: {
 AirPNRVM: @Html.Raw(Json.Encode(Model)),
PricingCommercialSkeleton:new Object(),
                  showFeeKendoWindow: function(e) {
 
                    },
 }
            });
 
 var templates = [
                {"path": rootUrl("Content/Templates/PricingWindow.tmpl.htm"), "tag":"PricingWindowTemplate"},
                {"path": rootUrl("Content/Templates/PricingCommercials.tmpl.htm"), "tag":"PricingCommercialTemplate"},
                {"path":rootUrl("Content/Templates/SharedTemplates.tmpl.htm")}
            ];
 
 templatesLoader.loadExtTemplates(templates);
});
</script>

 

FAREMVVM.js

function loadPricingWindowBinder() {
    debugger;
    kendo.ui.progress($("body"), true);
    kendo.bind($("#AirPricingContainer"), PricingViewModel.Item);
    kendo.bind($("#PricingGrids"), PricingViewModel);
 
    loadKendoWindowWithMaximize("#AirPricingDiv", "Pricing Window");
    $("#AirPricingDiv").data("kendoWindow").maximize();
    $("#AirPricingDiv").data("kendoWindow").restore();
    $("#AirPricingDiv").data("kendoWindow").maximize();
 
    kendo.ui.progress($("body"), false);
    debugger;
     pricingWindowFormValidator = $("#PricingForm");
    
 
}
 
$(document).bind("TEMPLATES_LOADED", function (e, path) {
    kendo.ui.progress($("body"), true);
    debugger;
 
    //alert("templates LOADED multiple");
    loadPricingWindowBinder();
    kendo.ui.progress($("body"), false);
});

 

KendoWindow.js

function DestroyTemplateMaximizedWindow(e) {
    debugger;
 
    $(e.sender.element).parent().remove();
    var tempname = "."+$(e.sender.element).attr("id") + "Script";
    $(tempname).remove();
}
 
function DestroyTemplateWindow(e) {
    debugger;
     
    $(e.sender.element).parent().remove();
    $(".KendoExtTemplate").remove();
}
 
 
 
 
    function loadKendoWindow (target,WindowTitle)
    {
        var myWindow = $(target);
        
        myWindow.kendoWindow({
            title: WindowTitle,
            visible: false,
            animation: false,
            modal:true,
            actions: [
                "Close"
            ],
            close: DestroyTemplateWindow
             
        }).data("kendoWindow").center().open();
    }
 
function loadKendoWindowWithMaximize(target, WindowTitle) {
    var myWindow = $(target);
 
    myWindow.kendoWindow({
        title: WindowTitle,
        visible: false,
        animation: false,
        modal: true,
        actions: [
            "Maximize", "Close"
        ],
        close: DestroyTemplateMaximizedWindow
 
    }).data("kendoWindow").center().open();
}


MultiTemplateLoader.js:

/**
This defines a Global object to serve loading external templates.
It handles multiple "Templates" (Or "Views") loading,
by operating on an array of JSON objects of type {path: "path to file", tag: "script's tag to attach to dom"}
 
This way-
 
you can load multiple templates, each with it's own tag so they can be referenced seperatly,
 
templates can be written in a much "cleaner" manner - as they are not wrapped by a "script" tag, IDE's will recognize the html.
 
A single event is raised after template loading has completed (loading & attach to DOM)
 
usage:
 
call "loadExtTemplates" on your array.
 
*/
 
 
var templatesLoader = (function($,host){
 
    /**
     * Name: rec_loadExtTemplates
     * Params:
     *   arr (JSON-Array): array of {path:"...", tag:".."}
     *   acc (string): accumulator
     *  
     * What do I Do ?
     *   Recursively traverse the JSON-Object array,
     *   for each object
     *    - try to "get" the template from path
     *    - if success
     *      - process a result (bound the result in <script> tag)
     *      - append result to accumulator
     *      - test if recursion end
     *         - true  - attach accumulator to "body" and trigger an event.
     *         - false - call recursively on smaller array.
     */
    var rec_loadExtTemplates = function(arr, acc) {
        var cur = $(arr).eq(0)[0];
        $.get(cur.path, function (result) { // On Success (done)
            //result = "<script id=\"" + cur.tag + "\" type=\"text/x-kendo-template\">".concat(result).concat("</script>");
            acc += result;
             
            arr = $(arr).slice(1);
            if(arr.length) {
                rec_loadExtTemplates(arr, acc);
            } else { // we're done
                $("body").append(acc);
                $(host).trigger("TEMPLATES_LOADED");
            }
        })
        // Uncomment for debug:
        /*
        .done(function() {
            alert("SUCCESS");
        })*/
        .fail(function(err) {
            alert("AN ERROR OCCURED: \"" + cur.path + "\" returned with status of \"" + err.statusText + "\"");
        });
    };
     
    /**
     * Name: loadExtTemplates
     * Params:
     *   templatesArray (JSON-Array): array of JSON-Object each with format: {path:"<path to template", tag:"<unique tag for template>"}
     *  
     * What do I Do ?
     *    Loads external template from path and injects in to page DOM
     *    Template will be injected in a <script type="text/x-kendo-template"> tag, and selected id value.
     *    browser does not run scripts with unknown types - thus it will not run this injected script !
     */
    return {
        loadExtTemplates: function (templatesArray) {
            rec_loadExtTemplates(templatesArray, "");
        }
    };   
         
})(jQuery, document);



 

0
Nencho
Telerik team
answered on 04 Oct 2017, 01:29 PM
Hello Neeraj,

I am afraid that we are unable to replicate the described issue, base on the provided code snippets. Probably the reason is that we had to strip it a lot, in order to get it runnable.

This is why, I would like to ask you to submit a separate support ticket, along with a runnable sample attached, as my colleague had previously suggested. Hence, we will be able to investigate the issue locally and pin down the reason for the multiple alerts.

Regards,
Nencho
Progress Telerik
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Neeraj
Top achievements
Rank 1
Veteran
answered on 06 Oct 2017, 04:13 AM
The reason might be when open window, the script loads and stays in DOM. but when close the script  get deleted. Hence when try to open window again, get alert from multiple copies of script. 
    Any solution for this ? to remove scripts when close  (i have scripts linked to view, that view open in )
0
Nencho
Telerik team
answered on 09 Oct 2017, 10:59 AM
Hello Neeraj,

Indeed, the reason might be exactly this. If you need to destroy the window widget, you should use the destroy method from its client API. Otherwise, the scripts hooked for the events and other operations will remain on the page and may cause the issue that you are experiencing.

Please refer to the following documentation article, demosntrating how to properly destroy the kendo widgets:

https://docs.telerik.com/kendo-ui/intro/widget-basics/destroy

Regards,
Nencho
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Neeraj
Top achievements
Rank 1
Veteran
answered on 10 Oct 2017, 04:58 AM
Hi Nencho, do call the destroy() method of (kendoWindow) on event of kendowindow as given in your link but have not use unbind() till now. It will just unbind object with dom element. I  think it will remove multiple
0
Nencho
Telerik team
answered on 11 Oct 2017, 12:04 PM
Hello Neeraj,

I am not sure that I had fully understood your last question. Could you please elaborate a bit more on your inquiry? However, the destroy() method performs the scripts removing from the page, which is responsible for the events subscription.

Regards,
Nencho
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Tags
MVVM
Asked by
Neeraj
Top achievements
Rank 1
Veteran
Answers by
Veselin Tsvetanov
Telerik team
Neeraj
Top achievements
Rank 1
Veteran
Nencho
Telerik team
Share this question
or