Created
November 17, 2011 11:56
-
-
Save piscis/1372991 to your computer and use it in GitHub Desktop.
Some KnockOut js data binding helper, to work a round a problem when setting values on in input fields via jQuery and knockout JS databinding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* hasKeyExists | |
* | |
* Searches for a hierarchical combination of keys in a json object | |
* | |
* @{Object} JSON Object | |
* @{String} path seperated with "." for example level1.level2.foo | |
* @return {Boolean} | |
*/ | |
var hashKeyExists = function(obj,path){ | |
var keys = path.split('.'); | |
var keyExists = function(obj,keyList){ | |
var cur = keyList.shift(); | |
if(obj.hasOwnProperty(cur)){ | |
if(keyList.length<=0){ | |
return true; | |
}else{ | |
return keyExists(obj[cur],keyList); | |
} | |
}else{ | |
return false; | |
} | |
}; | |
if(obj && typeof obj == "object" && keys.length>0){ | |
return keyExists(obj,keys); | |
}else{ | |
return false; | |
} | |
} | |
/** | |
* getBindingPath | |
* | |
* Returns the name of a knockout js data binding | |
* | |
* @elem {Mixed} jQuery selector sring or reference to a DOM node | |
* @return {Mixed} Undefined || String | |
*/ | |
var getBindingPath = function(elem) { | |
var bindingVal = jQuery(elem).data('bind'); | |
if(bindingVal!==undefined && bindingVal.indexOf(':')!=-1) { | |
var tmpList = bindingVal.split(':'); | |
if(tmpList.length==2) { | |
return tmpList[1]; | |
} else { | |
return undefined; | |
} | |
} else { | |
return undefined; | |
} | |
} | |
/** | |
* setBindingValue | |
* | |
* @param {Object} Binding store | |
* @param {Mixed} elem jQuery selector or dom reference where data binding exists | |
* @param {value} value to sed for the data binding | |
* @return {Boolean} | |
*/ | |
var setBindingValue = function(store,elem,value) { | |
var path = getBindingPath(elem); | |
if(hashKeyExists(ramonVM,path)) { | |
var recuVal = function(obj,keyList,val) { | |
var cur = keyList.shift(); | |
if(obj.hasOwnProperty(cur)) { | |
if(keyList.length<=0) { | |
if(typeof obj[cur] == 'function') { | |
obj[cur](val); | |
} else { | |
obj[cur] = val; | |
} | |
return true; | |
} else { | |
return recuVal(obj[cur],keyList,val); | |
} | |
} else { | |
return false; | |
} | |
} | |
return recuVal(store,path.split('.'),value) | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment