jQax jQuery plugin – The jQuery plugin version of the jQax ajax wrapper

Upgraded by popular demand, the jQax ajax wrapper has been turned into a full fledged jQuery plugin, conforming to the plugin authoring guidelines and compatible with compression.

Rain sweet code down on me:

Below is the full code as of writing, if you’re interested in helping out, the source can also be found here on github

Show me the usage:

Once you’ve referenced the script in the head section you can use the code like so:

var x = $.jQax({
    LoaderContainerId: "#divMyLoadingDiv",
    LoaderText: "I'm loading, wait up..."
});

Now you can perform the following function anywhere you need within scope of the above declaration:

var data = {
    myTrackRecord: "52 Seconds",
    activity: "go karts"
};
x.CallWebServiceWithJSON("MyWebService.asmx/Record", data, function (data, eventArgs) {
    var result = $.parseJSON(data.d); // Please note: You may not need ".d"
    // Do stuff here
});

The original non-plugin version of my code can be found in my previous post:

jQax – A Simple jQuery Ajax Wrapper with Loading Notification

newInfinity.jpg

Endless Scrolling ListView in Android

Not Uninfinity Implementing an endless scroller in Android was not actually that difficult. Here’s a quick code snippet and explanation to get you on your way.

Just give me the code!

Well here you go:

    public class EndlessScrollListener implements OnScrollListener {

        private int visibleThreshold = 5;
        private int currentPage = 0;
        private int previousTotal = 0;
        private boolean loading = true;

        public EndlessScrollListener() {
        }
        public EndlessScrollListener(int visibleThreshold) {
            this.visibleThreshold = visibleThreshold;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                    previousTotal = totalItemCount;
                    currentPage++;
                }
            }
            if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
                // I load the next page of gigs using a background task,
                // but you can call any function here.
                new LoadGigsTask().execute(currentPage + 1);
                loading = true;
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
    }

Ok, so all we’ve done is implement our own OnScrollListener named EndlessScrollListener, which can be called like so:

GigList.setOnScrollListener(new EndlessScrollListener());

Now Explain:

We start our class with a few private variables which perform the following functions:

  • visibleThreshold – The minimum amount of items to have below your current scroll position, before loading more.
  • currentPage – The current page of data you have loaded
  • previousTotal – The total number of items in the dataset after the last load
  • loading – True if we are still waiting for the last set of data to load.

Next we have a couple of constructors that allow us to set the visibleThreshold inline if we want.

The first overridden method we have is called every time the list is scrolled. This happens many times a second during a scroll, so be wary of the code you place here. We are given a few useful parameters to help us work out if we need to load some more data, but first we check if we are waiting for the previous load to finish.

If it’s still loading, we check to see if the dataset count has changed, if so we conclude it has finished loading and update the current page number and total item count.

If it isn’t currently loading, we check to see if we have breached the visibleThreshold and need to reload more data. If we do need to reload some more data, we execute a background task and set the loading flag to true. Thus solving the problem forever!

The last method in the class we do not need, however if you’re interested, it is primarily used for tracking changes in the scroll action itself via the scrollState parameter.

Finally, the code to call the class creates a new instance of EndlessScrollListener and bind’s it to a ListView of mine. Of course put your own ListView in place of GigList.

Pager Control

Simple MVC 2 Pager Control – PagerHtmlHelper

I’ve recently discovered a great new tool for MVC 2 that lets you create generic modular controls that can be shared with and used by anyone. So I built a paging control. Now you get a free Pager control AND learn how to build your own html helper. Amazing.

If you just want the pager control, do this:

  1. Download the three files from the following codeplex project I have created: http://pagerhtmlhelper.codeplex.com/
  2. Reference MvcUserControlHtmlHelpers.dll in your web application project.
  3. Place Pager.ascx into the App_Code folder in your web application. If you do not have an App_Code folder, just create one.
  4. Reference the PagerWrapper stylesheet in the head section of your html.
  5. Place the following snippet of code anywhere in any of your views and the pager will render right there:
<% Html.RenderPager([TotalItemCount],
       [PageSize],
       [PageIndex],
       Request.Url.Query,
       [BaseUrl - It can be relative]); %>

If you are interested how it works, read this:

So far with MVC 2, if you wanted to render a user control, you would use the RenderPartial method with a link to your control and possibly an accompanying model. The newly created (I’m a little slow, its actually been around since January) MvcUserControlHtmlHelpers library lets you create your own html helpers, complete with intellisense. It also lets you embed a user control absolutely anywhere in any of your views across the entire application with ease.

The beauty of this library is that we can now create simple modular user controls that anyone can quickly download and use. Let’s show you how:

Lets look at the entire code first:

<%@ Control Language="C#" Inherits="MvcUserControlHtmlHelpers.UserControlHtmlHelper" ClassName="CoolBlogs" %>

<script runat="server">
    // Declare Parameters Here
    public List<string> CoolBlogs;
    public int ShowItems;
</script>

<%    if (CoolBlogs.Count < ShowItems)
        ShowItems = CoolBlogs.Count;
%>

<div class="CoolBlogsWrapper">
    <ul>
    <% for (int i = 0; i < ShowItems; i++) { %>
        <li><%: CoolBlogs[i] %></li>
    <% } %>
    </ul>
</div>

Now comes the breakdown

To change our MVC User Control into a html helper, we just change the Inherits attribute to MvcUserControlHtmlHelpers.UserControlHtmlHelper and give the control a name via the ClassName attribute.

<%@ Control Language="C#" Inherits="MvcUserControlHtmlHelpers.UserControlHtmlHelper" ClassName="CoolBlogs" %>

You can add parameters to your control by adding the runat server script tags like below. You can use any public property as a parameter.

<script runat="server">
    // Declare Parameters Here
    public List<string> CoolBlogs;
    public int ShowItems;
</script>

Next you can add some server tags to run any C# code you need, before rendering the html.

<%    

    if (CoolBlogs.Count < ShowItems)
        ShowItems = CoolBlogs.Count;
%>

Finally, the rest is just like a regular user control, letting you add html and server tags as you like.

<div class="CoolBlogsWrapper">
    <ul>
    <% for (int i = 0; i < ShowItems; i++) { %>
        <li><%: CoolBlogs[i] %></li>
    <% } %>
    </ul>
</div>

Placing the following code into the App_Code folder of you web application, compiles the code into a single assembly, allowing you to call it from anywhere inside your app.

How do I call that sucker

Once placed into the App_Code folder, your new html helper can bee called by using the following code:

<% Html.RenderCoolBlogs(new List<string>() { “Benjii.Me”, “Lukencode”, “DkDevelopment” }, 3); %>

The great thing about the above code, is that it totally works with intellisense, furthering it’s usefulness as a generic control.

Javascript Classes are a Best Practice for Cleaner Javascript

Javascript classes allow you to create reusable javascript code and cleaner and leaner web sites and web applications. In this post we’ll create a javascript class and describe when and where you should use them.

Javascript Class Structure

Javascript classes are structured just like regular object oriented classes, they have a class signature, constructor, public properties, private variables and public and private methods. The following code is an example of how all these are laid out.


function myNotificationClass(myDefaultMessage) {    //Class Declaration

    // Private Variables
    var defaultMessage = "Hi there";

    //Public Variables
    this.NotificationCount = 0;

    //Constructor Start

    if (myDefaultMessage != “”)

    {

        defaultMessage = myDefaultMessage;

    }


 

    //Private Function

    function AddSignature(original) {

        return original + “ – By Ben Cull”;

    }

 

    //Public Function

    this.DisplayNotification = function(message) {

        alert(AddSignature(message));

    }

 

}

 

Now there are a few things to notice here so lets break this down and discuss each part separately.

Class Declaration

function myNotificationClass(myDefaultMessage) {
}

A class in javascript is created the same way as a regular function, it’s what we put inside the class that really makes it useful. To access the contents of the class, we need to instantiate it like so:

var note = new myNotificationClass(“im a default message”);

Constructor

Since the whole class is executed when the class is instantiated, adding some code inside the class but not inside any functions means that it will be run straight away. This mimics the purpose of a constructor and allows you to perform any setup for the class without the need for calling a function.

If you would like to pass in any parameters to the constructor, add them to the class declaration, like the above myDefaultMessage.

Private Variables and Methods

Private variables and methods are created the same way you would normally create them.


var defaultMessage = "Hi there"; 

 

function AddSignature(original) {

    return original + “ – By Ben Cull”;

}

These variables and methods can only be accessed from within the class itself, so they are useful for helper methods and keeping track of things you don’t want your page to see.

Public Variables and Methods

Public variables and methods are accessible anywhere that your instance is. eg. the “note” instance we created earlier.

Its important to note that public variables and methods are created by putting “this” in front of the declarations, like so:


this.NotificationCount = 0; 

 

this.DisplayNotification = function(message) {

    alert(AddSignature(message));

}

Also note that the function keyword now comes after the function name.

To call a public function or access a public variable, you must use the instance you created above.


var myCount = note.NotificationCount;

 

note.DisplayNotification(“Yes this is awesome”);

Why Should I Use Them?

The quick answer is code organisation and reusability.

Start by moving your global javascript functions into their own class. This will allow you to reference the file only once, but create as many instances of it in your pages as you like. If we took the myNotificationClass for example, this would allow you to create two separate default message displays with ease, like so:

var MessageDisplayerOne = myNotificationClass("I like hotdogs");

var MessageDisplayerTwo = myNotificationClass("Icecream is my favourite");

This opens up a world of opportunity for creating complex types within javascript.

Real World Example

Below are two real world examples I’ve used in some of my projects to help make life easier. Check them out if you’d like a better understanding of how javascript classes are implemented.

Map.debug
Ajax.debug

I hope this makes it easier to manage your javascript code. Drop me an email on the Contact Me page if you have any questions.