i’ve a jquery (UI) App here where the whole JQuery Code gets a little bit messy, so i started to think around how to structure this in a little bit fancier way… i read a blog post somewhere, that “oop” – in a java way can be achieved by doing some kind of this:
function RangeSelector(product_id) {
this.product_id = product_id;
this.start_point = "#from_" + product_id;
this.end_point = "#to_" + product_id;
}
RangeSelector.prototype.myFunction = function() { }
the whole code can be found here.
My Range Selector “Class” should hold two jquery ui datetimepickers that are responsible to let the user select a date time range for a shop where you can rent products
The problem that i currently have is the following: the date time pickers get callback functions (“unavailableFrom”, “unavailableTo”) where i’d like to do some specific things and then call a generic “unavailable” to function.
The error message is:
TypeError: 'undefined' is not a function (evaluating 'this.unavailable(date)')
I looked about that with firebug and it seems, that “this” not my object of the RangeSelector, but the HTML Element on what the datetimepicker is working.
My Question is: how can i access this method “unavailable”?
By the way, i tell you the whole story in here, because i don’t think, that the structure that i chose here is the right way to go. How do you handle these kind of things, where you have more than one html elements that have a common meaning and you would like to aggregate them?
If you need to set
thisto a different value, you can usejQuery.proxyto do that. (Or in an ES5-enabled environment, you can use the newFunction#bindfunction.)proxyaccepts a function and value to use forthis, and returns a function that will call the original withthisset to that value.So for instance, suppose you have your
RangeSelectorand you wantclickto triggermyFunctionon a specific instance:Now, when
r.myFunctionis called, within the call,thiswill be a reference to therobject. (If you need to know which DOM element was clicked, havemyFunctionaccept theeventargument that jQuery passes it, and useevent.target.)For completeness, the above using
Function#bind(if the browser supports ES5 features, or you’ve included an ES5 shim [sinceFunction#bindis shim-able]):More to explore (on my blog):
thisThe jQuery UI
datepicker‘sonSelectis a bit of a pain, because they don’t give you theeventobject and so you don’t have access toevent.target. Your best bet there is probably a closure that passes the element on:…where
myFunctionacceptsdateText,inst, andelementarguments.Live example | source
That works because the function we’re assigning to
onSelectis a closure over the environment containing thervariable.Closures are frequently misunderstood; FWIW, another blog entry: Closures are not complicated