Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Building a jQuery plugin, need to use a prototype

I'm currently working on building a plugin. IT is to allow users click on an image and leave a little annotation. I have it set up so that it can be called with something like

$('.imageselector').annot();

and you can then click around the image, leaving annotations around the place. These annotations are objects, with an x coordinate, y coordinate and an id.

I need to be able to give the user option to pass in pre-existing annotations, and so need to give them access to the Annotation prototype. The only way that I can find to do this is to create the annotation prototype outside of the plugin, but this doesn't seem great.

I've attempted putting the annotation prototype inside of the plugin, but haven't worked out how to do it and I haven't been able to use my google-fu to get any help. Does anybody have any suggestions or best practices for this?

Here is the relevant jQuery

// Set up JS object for each annot
function Annot(locX, locY, id) {
    this.locX = locX;
    this.locY = locY;
    this.id = id;
}

(function ($) {
    $.fn.annot = function (options) {
// STUFF

    return this;

}(jQuery));

This is in my HTML just before the closing body tag

<script>
var defaultAnnot1 = new Annot(0.6703125 , 0.764065335753176, 1);

$('.annotatableImage').annot({
  load: [defaultAnnot1]
});

</script>

2 Answers

I prefer using the jQuery UI widget factory since accessing JS object instances is a lot easier. Another way to access existing annotations is to use .data() to store instances.

Hmmm - maybe. I'm looking into Namespacing too. I couldn't find any Treehouse course which teaches Namespacing though.

Namespacing? You mean...

var NAMESPACE = NAMESPACE || {};
NAMESPACE.property = 'stuff';

Basicly that's all you need to know. :-)