Is this the best way of doing this. The sample code is a simple lookup of postnr (read zipcode). I'm trying to encapsulate all the client side logic inside one "class".
- Is this the way of doing callbacks? The this/that stuff sort of creeps me out a little
- Should the constructor just be a place where you declare variables? I have a init function call here that sets things up. But it is public and I wonder if there is some best practice around this?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var controller = new ClientController("postnr", "poststed");
});
var ClientController = function (postNr, postSted) {
this.postNrCtrl = $("#" + postNr);
this.postStedCtrl = $("#" + postSted);
this.init();
};
ClientController.prototype = function () {
// private variables/methods
var init = function () {
// Keep reference to this
var that = this;
// Setup event handling
this.postNrCtrl.change(function () {
that.getPostSted($(this).val());
});
};
var getPostSted = function (postnr) {
// keep reference context/this
var that = this;
$.getJSON("http://fraktguide.bring.no/fraktguide/api/postalCode.json?country=no&pnr=" + postnr + "&callback=?", function (data) {
that.postStedCtrl.val(data.result);
});
};
// public variables/methods
return {
init: init,
getPostSted: getPostSted
};
} ();
</script>
</head>
<body>
<label for="postnr">Postnr</label> <input type="text" id="postnr" />
<label for="poststed">Poststed</label> <input type="text" id="poststed" />
</body>
</html>