Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Tuesday, September 5, 2017

Back to the roots: defining a jQuery plugin in TypeScript

The problem

You're so proficient in TypeScript that you decided all your code will be type-safe. All that is left is this damn jQuery plugin that won't bow to your will and you have no idea how to make all the typing information work.

The solution

This is actually quite easy! Let's start with the obvious import:

    import * as $ from 'jquery'

Next you need to decide if your plugin will take configuration options. If that is the case then you need an interface describing those options

    interface FooOptions {
      color?: string
    }

Now we need to tell TypeScript that we're going to extend the global JQuery interface with our method:

    declare global {
      interface JQuery {
        foo(options?: FooOptions): JQuery
      }
    }

The question mark after options means this is an optional parameter and if not defined then an undefined value will be passed on

All that is left is to write the plugin itself

    $.fn.foo = function(this: JQuery, options?: FooOptions) {
      const settings: FooOptions = {
        color: 'blue',
        ...options,
      }
      return this.each(function() {
        $(this).css({ 'background-color': settings.color })
      })
    }

The method signature tells TypeScript that this in this context is a jQuery object and that there can be a FooOptions passed on.

The rest is obvious: using object spread operator we get the actual set of settings and next we just go on with the plugin's body.

Happy coding!

Tuesday, January 3, 2012

jQuery and posing JSON data to the server

Today a good friend of mine asked me how to post JSON data to the json-rest-api plugin using jQuery. As it turned out using $.post() doesn't do the trick...

Well it's not impossible but very inconvenient if you have to do it a lot. First you need to use the $.ajax() method, not the $.post() one. Secondly you need to specify the contentType parameter for the receiver to be notified that the data is in that format. And last but not least it is crucial to properly serialize your object to string.

The last part can be done using JSON.stringify() but writing this over and over again is painful. Here's a gist (raw) you can use that adds a sister version of $.post called $.postJSON that does exactly the same thing as the original one but sends data in JSON format instead of form post.

Parameters are exactly the same with the single difference that the default expected data format is "json", which makes sense if you're working with JSON services.

Happy coding!

Thursday, January 6, 2011

Story of one Grails plugin

It's been one of those days where I felt like I need to create a spike app just to prove things are simple in Grails. A friend of mine is preparing a presentation about using NOSQL databases in applications and since it's pretty darn simple to use MongoDB in Grails I've decided to put together a sample that will utilize this datastore.

It all started soooo simple...

grails create-app example
grails uninstall-plugin hibernate
grails install-plugin mongodb
grails create-domain-class Person
grails create-controller Person
grails create-controller Home

Then I've edited the domain class to have 2 properties firstName and lastName, added scaffolding to the PersonController... Basically the Grails 101 stuff...
The HomeController was also pretty simple. Just the index action that returned the [ people: Person.list() ] map and the view that rendered a table to present this data...

Then the geek kicked in...


I thought: now wouldn't it be nice to have the table sortable? Well, sortable but the sorting itself should be done using Ajax - now that'd be cool :)

Right tool for the job - jQuery


When I think "Ajax" it's as if I'd be thiking jQuery at the same time. For me there's nothing else. Period :)

To do that I first needed to extract the part that rendered <tbody> to a separate template _rows.gsp. Then another action, rows was needed to return sorted list of rows instead. That was again dead simple with GORM:
render template: 'rows', model: [ 
people: Person.list(sort: params.key, order: params.order)
]

Then the actual client-side jQuery magic happened:
$("th").click(function() {
var key = $(this).attr("column");
var order = $(this).attr("order");
$(this).siblings()
.removeClass("order-desc")
.removeClass("order-asc")
.removeAttr("order");
if (order == "desc") {
$(this).attr("order", "asc")
.removeClass("order-desc")
.addClass("order-asc");
} else {
$(this).attr("order", "desc")
.removeClass("order-asc")
.addClass("order-desc");
}
$(this).parents("table").find("tbody")
.load("${createLink(controller: 'home', action: 'rows')}?order=" +
order + "&key=" + key);
});

It's all basic stuff... Nothing to be proud of...

Geeky thinking part 2


A simple idea to turn the code above into a jQuery plugin turned out to be the hardest part. First of all, authoring jQuery plugin is not as simple as I'd like it to be. I'm more of a "File - new" person than "Google, google, google..." one. So after I've finally found out how to create such a plugin I was pretty much exhausted.
But what if it'd be really simple? Something along the line of "File - new" or (in the case of Grails) "grails create-jquery-plugin my-plugin"???

And so I've created the jquery-plugin-authoring Grails plugin. From now on whenever I see that part of my application just fits like a jQuery plugin I simply create one. The template leads me every step of the way (the initialization, default values for options, a method to override them, a list of possible messages my plugin can respond to).

And life is simple again :)

End result


I love to see my results be better than someone else's. In this case comparing what it takes to do all that in pure Java having to glue together Hibernate in Entity Manager mode to use Hades, wiring it all with spring beans and adding the web application part with Wicket seems like tons of work by comparison. In fact It took me about 4 hours from the very beginning to the point where I've had the plugin released, used and all was nice and dandy. Grails rule!

I wonder how much time it'd take to do the same in Ruby on Rails? If any of you could perform such an experiment and share the result it'd be really great!

Wednesday, January 20, 2010

jQuery 1.4 Released!

Hi there,

in case you have missed that a new version jQuery (my favorite JavaScript library) has been released. It's the 1.4!

Go check the latest stuff on jQuery at jquery14.com


Sunday, May 31, 2009

Flexigrid

Did you ever wanted to have an all-in-one solution for grids in your application? One that does Ajax refreshes, supports sorting, filtering and pagination out of the box. How about an API that's actually usable?

I've got some good news for you - it's there! It is called Flexigrid and is in fact a plugin for jQuery.

For the purpose of demonstration I've put together an example that does pretty much everything I've mentioned above.

FlexigridExample.zip

Here are some points worth noticing in the provided example:

1. The CSS in Internet Explorer is trashed. I don't know how to fix it.
2. The real power that feeds the data is to be found in BookController and is well documented.
3. Since there's not much documentation for Flexigrid itself I suggest taking a look at the list of options in flexigrid.js.

Enjoy this fantastic library!