2013-06-07 2 views
1

jQuery 유효성 검사 플러그인에 많은 문제가 있으며이 문제를 해결할 수있는 유일한 방법은 .submitHandler 속성을 사용하고 내부에서 일부 트릭을 수행하는 것입니다.데이터 속성에서 객체로 문자열을 구문 분석

트리거의 부모가 필드 집합인지 확인하는 중이고 data-submit-handler 특성이 있으면 거기에 보내는 모든 항목이 실행됩니다.

그것은 다음과 같이 보일 것입니다 :

<fieldset data-submit-handler="SITE.Products.QA.Bindings.post"> 

하는 경우에는 SITE.Products.QA.Bindings.post는 기능 할 것이다. 문제는 제가 참조하는 함수를 실행할 수 있도록 문자열을 객체가 아닌 데이터 속성에서 파싱하는 방법을 모른다는 것입니다. 그것을 할 수있는 방법이 있습니까?

당신은 도우미를 사용할 수 있습니다
+0

내가 같은 질문을하지 않아도, 나는 같은 개체의 인식 아니에요 위의 질문에 설명되어 있습니다. – Roland

+0

을 통해서만 문자열을 보낼 수 있습니다. 개체에 대한 참조가 전혀 없습니까? 'SITE'는 변수가 아닙니다. –

+0

제출 처리기가 처리되는 시점에서 아니요, 모든 코드 이전에 제공됩니다. 플러그인 조작 부분입니다 – Roland

답변

1

은 그것을 해결할 수 :

// convert string representation of object in to object reference: 
// @p: object path 
// @r: root to begin with (default is window) 
// if the object doesn't exist (e.g. a property isn't found along the way) 
// the constant `undefined` is returned. 
function getObj(p, r){ 
    var o = r || window; 
    if (!p) return o;      // short-circuit for empty parameter 
    if(typeof p!=='string') p=p.toString();// must be string 
    if(p.length==0) return o;    // must have something to parse 
    var ps = p.replace(/\[(\w+)\]/g,'.$1') // handle arrays 
       .replace(/^\./,'')   // remove empty elements 
       .split('.');     // get traverse list 
    for (var i = 0; i < ps.length; i++){ 
     if (!(ps[i] in o)) return undefined; // short-circuit for bad key 
     o = o[ps[i]]; 
    } 
    return o; 
} 

// couple extensions to strings/objects 

// Turns the string in to an object based on the path 
// @this: the string you're calling the method from 
// @r: (optional) root object to start traversing from 
String.prototype.toObject = function(r){ 
    return getObj(this,r); 
}; 

// Retrieves the supplied path base starting at the current object 
// @this: the root object to start traversing from 
// @s: the path to retrieve 
Object.prototype.fromString = function(p){ 
    return getObj(p,this); 
}; 

그래서, 예를 들어, 사용 :

window.foo = { 
    bar: { 
     baz: { 
      hello: 'hello', 
      world: function(){ 
       alert('world!'); 
      } 
     } 
    }, 
    list: [ 
     {item: 'a'}, 
     {item: 'b'}, 
     {item: 'c'} 
    ] 
}; 

var a = 'foo.bar.baz.hello'; 
console.log(getObj(a)); // hello 
console.log(a.toObject()); // hello 

var b = 'foo.bar.baz.world'; 
console.log(getObj(b)()); // world 

var c = 'baz.hello'; 
console.log(getObj(c, foo.bar)); // hello 
console.log(foo.bar.fromString(c)); // hello 
console.log(c.toObject(foo.bar)); // hello 

var d = 'foo.list[1].item'; 
console.log(getObj(d)); // b 
관련 문제