I am using Jquery $.each to get all the elements which belong to a particular class and I wanted to call a function on each of those one after another.To achieve this, I called following function:
var elements = $('.colorpickerHolder');
elements.each(self.ApplyColorPicker());
I can see on the runtime that elements has three elements which is correct. Now, when I call self.ApplyColorPicker, I am refereing to each current element with $(this). Surprisingly, $(this) is not current element.
My code is working under knockout framework and both pieces of code are under a viewModel. and inside ApplyColorPicker $(this) becomes my viewModel. I am not sure why is that. Any reasonings?
Below is my ApplyColorPicker code just of the review:
self.ApplyColorPicker = function () {
$(this).ColorPicker({
color: '#0000ff',
onShow: function (colpkr) {
$(colpkr).fadeIn(500);
return false;
},
onHide: function (colpkr) {
$(colpkr).fadeOut(500);
return false;
},
onChange: function (hsb, hex, rgb) {
$(this).css('backgroundColor', '#' + hex);
}
});
};
Pass in a reference to the function itself to
each, not what the function evaluates to. In other words useself.ApplyColorPickerinstead ofself.ApplyColorPicker().