I have finally been able to create my little navigation plugin in an object-oriented way that reads the li
from a JSON file.
Now, is my code efficient? Especially, the click function within getRegion
function?
Is this the correct way to handle the click events in OO?
Here's is working version: PLNKR
'use strict';
if (typeof Object.create !== 'function') {
Object.create = function (obj) {
function F () {
}
F.prototype = obj;
return new F ();
};
}
(function ($, window, document, undefined) {
var Navigation = {
init: function (options, elem) {
var self = this;
self.elem = elem;
self.$elem = $ (elem);
self.url = 'data.json';
self.navigation = ( typeof options === 'string' )
? options
: options.navigation;
self.options = $.extend ({}, $.fn.drawNavigation.options, options);
self.cycle ();
},
cycle: function () {
var self = this;
self.fetch ().done (function (results) {
self.buildFrag (results);
self.display ();
self.getRegion ();
});
},
buildFrag: function (results) {
var self = this;
var navigationRegion = self.options.navigation;
self.list = $.map (results[navigationRegion].navigation, function (obj, i) {
return $ (self.options.wrapEachWith).append (obj);
});
},
fetch: function () {
return $.ajax ({
url: this.url
});
},
display: function () {
this.$elem.hide().html (this.list).fadeIn(800);
},
activate: function (item) {
$ (item).siblings ().removeClass ('flag-active');
$ (item).addClass ('flag-active');
},
getRegion: function () {
var self = this;
$ ('#flags').find ('div').on ('click', function () {
//activate flag
self.activate (this);
self.options.navigation = $ (this).attr ('id').split ('_')[0];
self.fetch ().done (function (results) {
self.buildFrag (results);
self.display ();
});
});
}
};
$.fn.drawNavigation = function (options) {
return this.each (function () {
var navigationBar = Object.create (Navigation);
navigationBar.init (options, this);
});
};
//default
$.fn.drawNavigation.options = {
navigation: 'uk',
wrapEachWith: '<li></li>'
}
}) (jQuery, window, document);
$ (function () {
$('#navigation').find('ul').drawNavigation({});
});