Context changes on the call of $.each() function

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);
                }
            });
        };

Answers


Pass in a reference to the function itself to each, not what the function evaluates to. In other words use self.ApplyColorPicker instead of self.ApplyColorPicker().

 var elements = $('.colorpickerHolder');
 elements.each(self.ApplyColorPicker);

It looks like you are calling ApplyColorPickers in the .each statement, meaning it is only being called once and is passing the result of that function into .each, rather than a reference to the function. This should work instead:

elements.each(self.ApplyColorPicker); //Without the () after ApplyColorPicker

Need Your Help

How i can get the value of cell in datagrid in wpf?

c# wpf datagrid

I have a datagrid, with a number of rows. I want to get the value of cell[0].

Detect which childwindow of the foreground window has been clicked?

c# winapi childwindow

My task was to to find the foreground window (accomplished using GetForegroundWindow API) and then I had to pre-populate a list which contained all the child windows of the foreground window

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.