Four_lo
Four_lo

Reputation: 1150

Problems loading external script that worked when I loaded it from my view

The script initially sat on my EJS view tucked in between some nice script tags. I moved it to an external file and initially it did not work at all, my on click listener did nothing. I then moved it down to the bottom of the page right outside of the body tag and that allowed it to work sometimes and when it did work it was much slower than before. This is the first time I have used pageinit instead of document.ready, I am assuming that is why I can not figure out what my problem is. Here is the code. Thanks for any help.

var currentList;
var elementID;
var id;

$('#mowingmaster').on('pageinit', function (event) {

    $('li').each(function (index) {

        var elementID = $(this).attr('id');
        elementID = '#' + elementID;

        $(function () {
            $(elementID).click(function (event) {

                var elementID = $(this).attr('id');
                id = elementID;
                elementID = '#' + elementID;

                setElementID(id);
                $.mobile.changePage("#dailylist");
            });
        });
    });

    $("#dailylist").on("pagebeforeshow", function (event, ui) {
        $("#testhide").hide()
        setCurrentList(elementID);
    });

    $("#dailylist").on("pageshow", function (event, ui) {

    });
});

function setElementID(id) {
    id = id;
}

function setCurrentList() {

    var currentList = id;

    $.ajax({
        type: "POST",
        url: "/scape/mowinglist",
        data: {
            currentList: currentList
        },
        success: function (data) {

        }
    });
};

Upvotes: 0

Views: 54

Answers (1)

C3roe
C3roe

Reputation: 96382

This is the first time I have used pageinit instead of document.ready

$('#mowingmaster').on('pageinit', function (event) {

For that to work, the element #mowingmaster must exist already when that snippet is run – if it doesn’t, the selector just returns nothing, so there is nothing to bind events to with on.

document.ready is used differently – you normally use that to just start executing code when the document is ready, and then you bind your events within that code.

Please look at the docs for pageinit:

$( document ).on( "pageinit", "#aboutPage", function( event ) {

they are binding this event to document here and provide a selector for the element that something should be done with (#aboutPage) – and that’s the way you should use it as well. (document is “always” available right from the start, whereas DOM elements might not exist already at the point your script executes.)

Upvotes: 1

Related Questions