Search code examples
javascriptjquerydomscopemodule-pattern

javascript module pattern works on jsbin but not in my server/browser


I am a backend developer, I write javascript only when needed and in not the best ways. But I wanted to redeem myself and star writing organized and following best practices as much as I could.

So I started a module pattern to encapsulate some functions and bind UI events from my markup, becuase this was pretty much try and error, I used jsbin following the suggestion of a friend who is a front end developer.

The thing is, that my concept works on jsbin, but then I moved that to my js file in the server and there it seems I loose scope of the jQuery objects that I cache inside my module pattern.

http://jsbin.com/ciwomeve/7/edit

The functionality is pretty basic I populate the options of two select elements (this works) then I bind the on change events for those selects, and when triggered I should call some functions that eventually should do an ajax request to my backend and obtain data.

Can you guys please advise me on the code, and tell me what I am doing wrong please?


Solution

  • There's not much to go on here, but I'm fairly certain that your issue is that your script tag is in <head>, and it's running before your content is loaded. If this is the case, it will be trying to access elements in the DOM that don't yet exist (e.g. when this line runs, $hostSelect1: $('#host-select-1') the select element with id host-select-1 won't exist yet, but jQuery will look for it anyway and fail silently).

    You can move your script to the bottom of the page, right before </body>, in which case you can be certain that all of your content will be loaded when your script runs. This method also has some other performance benefits. Or else you can wrap your call to DbDiff.init() in $().ready, like this $().ready(function(){DbDiff.init()});, which will have largely the same effect (except that settings has already been evaluated... you would need to do a little restructuring in order to make sure $('#host-select-1'), etc. are evaluated and assigned to $hostSelect1 only after your DOM content has loaded).