Quantcast
Channel: Devlicio.us - Just the Tasty Bits
Viewing all articles
Browse latest Browse all 40

Pro Tip – When defining Custom Knockout Validation rules Wrap them in a Self Calling Anonymous function

$
0
0

While setting up my coding examples for my next Pluralsight course on InDepth Knockout Validation (check out my HTML for Xaml Dev or Knockout for Xaml Dev) I was stumped because my custom validators were not working as expected.  In fact they were not working at ALL.

As I started to debug my code I set a few break points and immediately I saw the issue.  The initialization of my custom rules was being hit AFTER my view model was bound to my context

I had my Rules setup as follows:

image

 

Any my VM Binding setup as follows:

image

Given that I knew the order execution of my code was not right, does any one know why?  I mean I did reference the .js for my rule prior to my inline function. 

Well the reason was that I was not being consistent. In my rule I was using jQueries Document Ready but in my view I was using a Self Executing function. And the issue is that the jQuery Document ready will be executed AFTER the DOM is completely loaded while the Self Executing function will execute immediately.. DOH  I knew this was how the 2 worked but my inconsistent coding habits got me in trouble.

Once I wrapped my rule in an Self Executing function as below the world was a happy place, for me at least.

image

Till next time,


Viewing all articles
Browse latest Browse all 40

Trending Articles