I don't do much in the ways of object-oriented Javascript so for a script I had to write I decided to take an OO approach to better learn how it works.
I have an object called Page that defines some methods, two of which define behaviors of a page using the this
variable. Eg.
var app = app || {};
app.PageType = {
FIRST : 0,
MIDDLE : 1,
LAST: 2
};
app.Page = function(pageId, pageType, categoryItems) {
this.pageType = pageType;
this.pageId = pageId;
this.categoryItems = categoryItems;
};
app.Page.prototype = {
constructor: app.Page,
someMethod: function(domDiv) {
},
establishListeners: function() {
$('#Page' + this.pageId + ' > .pageNavigatorLeft').on('click', app.Page.navigateLeft);
$('#Page' + this.pageId + ' > .pageNavigatorRight').on('click', app.Page.navigateRight);
},
navigateLeft: function(e) {
var newPage = $('#Page' + (this.pageId - 1));
var oldPage = $('#Page' + this.pageId);
oldPage.fadeOut(2000);
newPage.fadeIn(2000);
},
navigateRight: function(e) {
var newPage = $('#Page' + (this.pageId + 1));
var oldPage = $('#Page' + this.pageId);
oldPage.fadeOut(2000);
newPage.fadeIn(2000);
}
}
The code sample above shows what I am attempting to do with the establishListeners
method. Clearly this doesn't work because even if I could assign the app.Page
object navigate methods as Function handlers for a jQuery event, then the this
variable will refer to the anonymous function and not the specific app.Page
object instance that I want this function to emulate.
Could I can wrap this with an anonymous function and pass the app.Page
object instance into its own method? I don't really want to define the navigation behaviors outside of the app.Page
class because this goes against the OO principle of object classes defining their own behaviors.
If what I am trying to do is a limitation of Javascript then I can accept this, but I doubt that Javascript could actually be so fundamentally, intrinsically, and sickeningly limited in its OO support so I must be making a stupid mistake here.