Objective way to create objects and manage object’s behavior with JQuery.
To define a new object with JQuery Objects use the define method. Each JQuery Object has three attributes:
- structure – Defines the html structure of the object.
- defaults – These are the default values of options passed to the structure.
- behavior – Defines how the object will behave.
In the example defines a new objects named “photo_tile”. Which displays a photo and when you click on the photo alerts you of it’s title.
$.objects.define('picture_tile', {
structure: function(options) {
this.image = $('<img/>', {src:options.photo_url, alt:photo_title})
return $('<div/>', { html:this.image, class:photo_tile });
},
defaults: {'photo_tile':'Untitled',
'photo_url':'/images/missing.png'},
behavior: function(options) {
this.click(function() {
alert('This image is named '+$('img',self).attr('alt'); )
});
}
});
Now that we have an object defined we can make a new one. To make a new “photo_tile” we use the make() command:
var new_photo_tile = $.objects.make('picture_tile', { src:'/images/1.png', alt:'My trip to Vegas' });
$('body').append(new_photo_tile);
You can also use the “photo_tile” object to add functionality to already existing DOM elemenets:
To just add the behavior of an Object:
$('.photo').behaveLike('photo_tile');
Or you can use html attributes on existing DOM elements to define new instances of an Objects. Imagine you have the following HTML:
<div class='placeholder' photo_url='/images/2.png' photo_title='My trip to New York'>Loading Image...</div>
You can make your placeholder element into a new Object:
$('.placeholder').makeInto('photo_tile');