2014-11-05 39 views
0

我有一個插件,我剛纔寫的,這是迄今爲止只是我希望開發時的行爲。我試圖將這些代碼從我的腳本目錄中取出併發布到Codepen.io上。在運行時出現腳本錯誤,錯誤是無法讀取未定義的'Action'。它通過傳遞事件的單擊事件來實例化。兩者都使用jQuery 2.1。任何人都知道這裏發生了什麼?Jquery插件無法在codepen上工作,在其他地方效果很好

繼承人的codepen:上的jsfiddle

http://codepen.io/nicholasabrams/pen/uJKrL

// $ DOC 
$.fn.dataValidate = function(event, userSettings) { 
    "use strict"; 
    event.preventDefault(); 
    var api = { 

     // Script definition defaults defined in object below 

     notNull: { 
      errorText: 'This field is required', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 
       if (dataToCheck === '' || dataToCheck === null || dataToCheck === 'undefined' || dataToCheck.length === 0) { 
        // if true return true to caller 
        alert('null'); 
        // Retrieve errorText 
        // Wrap in error template 
        this.errorForNotNull = new api.ErrorInjector(instance); 
        return false; 
       } 
       else { 
        return true; 
       } 
      } 
     }, 
     isNaN: { 
      errorText: 'Numbers not allowed here', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 

        api.notNull.Action(dataToCheck, instance); /* Reuse the notNull method as a screening service before entering into the method specific filtering (assuming null fields would be inappropriate in any types of check) */ 
        if (isNaN(dataToCheck)){ // Check if the not null field is also non a number 
            return true; 
        } 
        else { 
        this.errorForIsNan = new api.ErrorInjector(instance); 
        return false; 
        } 
       } 
     }, 
     isNum: { 
      errorText: 'Please enter a number', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 
       api.notNull.Action(dataToCheck, instance); 
        if (!isNaN(dataToCheck)){ // Check if the not null field is also non a number 
            return true; 
        } 
        else { 
        this.errorForIsNan = new api.ErrorInjector(instance); 
        return false; 
        } 
      } 
     }, 
     isEmail: { 
      errorText: 'Please enter a valid email address', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 
       api.notNull.Action(dataToCheck, instance); 
       var checkEmailRegEx = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 

       if (checkEmailRegEx.test(dataToCheck)){ 
       } 
       else { 
       this.errorForIsEmail = new api.ErrorInjector(instance); 
       } 

      } 
     }, 
     isPw: { 
      errorText: 'Please enter a password', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 
       api.notNull.Action(dataToCheck, instance); 
       console.log(dataToCheck); 
       if (dataToCheck.length > 4){ 
        var isPwRegEx = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/; 
        if(isPwRegEx.test(dataToCheck)){ 
         // Multiple pw checkpoints here 
         // At least one upper case English letter 
         // At least one lower case English letter 
         // At least one digit 
         // At least one special character 

         return false; 
        } 
        else { 
         this.errorForIsPw = new api.ErrorInjector(instance); 
         return true; 
        } 
        } 
       } // End length check for isPw 


     }, 
     isPhoneNumber: { 
      errorText: 'Please enter a valid phone number', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 
       api.notNull.Action(dataToCheck, instance); 
       this.errorForIsPhoneNumber = new api.ErrorInjector(instance); 
      } 
     }, 
     isUsername: { 
      errorText: 'Please enter a valid username', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 
       api.notNull.Action(dataToCheck, instance); 

       var checkUsernameRegEx = /^[a-zA-Z0-9.\[email protected]*!]{3,30}$/; 

       if (checkUsernameRegEx.test(dataToCheck)){ 
       alert('valid username'); 
       } 
       else { 
       this.errorForIsEmail = new api.ErrorInjector(instance); 
       } 
      } 
     }, 
     isNamePart: { 
      errorText: 'Please enter a valid name', 
      symbol: false, 
      Action: function(dataToCheck, instance) { 
       api.notNull.Action(dataToCheck, instance); 

       var checkNamePartRegEx = /^[a-zA-Z ]+$/; 

       if (checkNamePartRegEx.test(dataToCheck)){ 
       alert('valid name part'); 
       } 
       else { 
       this.errorForIsEmail = new api.ErrorInjector(instance); 
       } 
      } 
     }, 
     // New method would be added here 
     errorOutput: 'validated', 
     targets: ['[data-validate="notNull"]', '[data-validate="isNaN"]', 
      '[data-validate="isNum"]', '[data-validate="isEmail"]', '[data-validate="isPw"]', '[data-validate="isPhoneNumber"]', '[data-validate="isUsername"]','[data-validate="isNamePart"]'], 
     // Target selectors, can be modified on initialization to that of your liking, as well as have new ones added. Add a new selector target at the end of the array above 
     placeholder: { 
      // Template shared by each validation output error 
      template: { 
       defaultPlaceholderContainerStyle: 'position: relative;background:#ccc;', 
       defaultPlaceholderStyle: 'position: absolute;left:0;top:0;width:100%;line-height:26px;height:100%;', 
       // The above styles may be easily detached by simply tranfering the above CSS to a style rule matching the errorOutput class outlined above in this same object, or set on instantiation 
      }, 
     }, 
     ErrorInjector: function(instance) { 
      var errorNs = instance.data('validate'); 
      var error = '<div data-validate="output" class="' + api.errorOutput + '">' + api[errorNs].errorText + '<\/div>'; 
      instance.wrap('<div data-validate="output_container" class="' + api.errorOutput + '_container"><\/div>'); 
      instance.before(error); 
     }, 
     acceptedTypes : ['input[type="text"]','input[type="email"]','input[type="password"]','input[type="checkbox"]','input[type="radio"]','input[type="tel"]'], 
     results: {} // NS for all validation results and debugging info (see below) 
    }; 
    // Merge the caller sent options object with the defaults. Any options set in on init from the caller will overwrite the default/internal settings 

    this._overrideApiWithUserSettings = (function() { 
     $.extend(true, api, userSettings); 
    })(); 

    var targetsAll = api.targets; 

    // Private utility for removing the validationOutput errors from the DOM 
    this._removeThisErrorFocusThisInput = function() { 
     var activeOutputPlaceholder = $(this); 
     activeOutputPlaceholder.unwrap(); 
     activeOutputPlaceholder.remove(); 
     $.each(api.acceptedTypes, function(){ 
     var eachTypeInAcceptedTypes = this; 
      activeOutputPlaceholder.find(eachTypeInAcceptedTypes).focus(); 
     }); 

     $('body').unbind('click', '.' + api.errorOutput); 
    }; 

    $('body').on('click', '.' + api.errorOutput, this._removeThisErrorFocusThisInput); 

    // Fire each module off conditionally, based on the presence of the targets set on init 

    this._instantiateByDataValues = (function() { // The core of the script, carefully loadings only each modular bit of functionality by its request in the DOM via data-validate="" 

     $.each(targetsAll, function(/*iteration*/) { /* Iterate through all of the selectors in the targets array, doing the following with each instance of them found in the DOM, passing iteration for debugging purposed only */ 
      var selectorTargetFromArray = $(this); 
      $.each(selectorTargetFromArray, function() { 
       var instance = $(this), 
        thisFnFromDomDataAttrNS = instance.data('validate'); 
       if (instance.length) { // If any of the selectors in the targets array are found to be in the the DOM on init 

        // Fire the constructor on the element with the data-validate="thisMethod", while passing its value to its action (all method modules and method specific functionality is named based on the selector that is responsible for its instantiation) 

        this.executeActionByCallerName = new api[thisFnFromDomDataAttrNS].Action(instance.val(), instance); 
        //! This fires off the action of the module itself off by the name of the value in the data-validate="functionNameHere"  
       } 
       else { 
        this._createNoRunLog = api.results[this] = false; // Store refs to any built in methods not used for your debugging pleasure, under the name it is called by and on 
        console.log(api.results); 
       } 
      }); 
     }); 
    })(); 
    return this; 
}; // End preValidation module 
+0

我的第一個猜測是某種競爭條件與jQuery UI小部件過程中的步驟。仔細檢查您將「驗證」數據附加到對象的位置,並確保在您運行'_instanciateByDataValues'方法時已將其附加。 – Demonslay335 2014-11-05 00:58:29

+0

哦,當我運行你的CodePen時,它使用jQuery 1.11.0和jQuery UI 1.10.4。因爲你說你正在運行jQuery 2.1,所以可能是一個兼容性差異。 – Demonslay335 2014-11-05 01:00:53

+0

我試過用外部負載(沒有內置方法的jQuery),這也是我的想法!我實際上只使用jQuery(沒有用戶界面),不在這個項目上使用他們的widget工廠方法 – NicholasAbrams 2014-11-05 01:03:46

回答

0

工作正常.. http://jsfiddle.net/exsfabxr/我想我可以排除我的代碼爲這裏的問題?似乎這是一個內部的Codepen.io問題?

$(function(){ alert('same code as above, i just wrote this because of stackoverflows "smart" validation'); window.location.href = 'http://jsfiddle.net/exsfabxr/'; }); 
相關問題