티스토리 뷰
/**
* Object Speaker
* An object representing a person who speaks.
*/
var Speaker = {
init: function(options, elem) {
// Mix in the passed in options with the default options
this.options = $.extend({},this.options,options);
// Save the element reference, both as a jQuery
// reference and a normal reference
this.elem = elem;
this.$elem = $(elem);
// Build the dom initial structure
this._build();
// return this so we can chain/use the bridge with less code.
return this;
},
options: {
name: "No name"
},
_build: function(){
this.$elem.html(''+this.options.name+'
');
},
speak: function(msg){
// You have direct access to the associated and cached jQuery element
this.$elem.append(''+msg+'
');
}
};
// Make sure Object.create is available in the browser (for our prototypal inheritance)
// Courtesy of Papa Crockford
// Note this is not entirely equal to native Object.create, but compatible with our use-case
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {} // optionally move this outside the declaration and into a closure if you need more speed.
F.prototype = o;
return new F();
};
}
(function($){
// Start a plugin
$.fn.speaker = function(options) {
// Don't act on absent elements -via Paul Irish's advice
if ( this.length ) {
return this.each(function(){
// Create a new speaker object via the Prototypal Object.create
var mySpeaker = Object.create(Speaker);
// Run the initialization function of the speaker
mySpeaker.init(options, this); // `this` refers to the element
// Save the instance of the speaker object in the element's data store
$.data(this, 'speaker', mySpeaker);
});
}
};
})(jQuery);
$.plugin = function(name, object) {
$.fn[name] = function(options) {
// optionally, you could test if options was a string
// and use it to call a method name on the plugin instance.
return this.each(function() {
if ( ! $.data(this, name) ) {
$.data(this, name, Object.create(object).init(options, this));
}
});
};
};
$(function(){
// Call a custom plugin for your object on a dom element
$('#mySpeaker').speaker({'name': 'Alex'});
// Have quick access to the actual speaker object
var mySpeaker = $('#mySpeaker').data('speaker');
// The interface of the object that you build can
// wrap more complex dom manipulations that are
// separated from actual program logic.
mySpeaker.speak('I am a speaker _ vava .'); // Results in a dom update
// This shows automatic access to correct element in the dom
// With the Speaker object, we could essentially do this:
$.plugin('speaker', Speaker);
// At this point we could do the following
$('#myDiv').speaker({name: "Alex"});
});
댓글