javascript - knockoutjs passing value when using foreach inside of with binding throws reference error -
i'm trying dynamically create select inputs using knockoutjs.
my view looks -
<div data-bind="with: questionfilter"> <form> <div> <select data-bind="options: categories, optionstext: 'name', optionsvalue: 'categoryid', value: selectedcategory"> </select> </div> <div data-bind="foreach: details"> <select data-bind="options: subcategories, optionstext: 'name', optionsvalue: 'categoryid', value: selectedsubcategory"> </select> </div> </form> </div> <script type="text/javascript"> ko.applybindings({ categories = <?php echo json_encode($categories); ?>, details = ko.observablearray([]) }); </script> and js looks -
function questionfilter(categories, details) { var self = this; self.categories = ko.observablearray(categories); self.subcategories = ko.observablearray([]); self.selectedcategory = ko.observable(); self.selectedsubcategory = ko.observable(); self.supersubcategories = ko.observablearray([]); self.selectedcategory.subscribe(function(category) { function search(namekey, myarray){ (var i=0; < myarray.length; i++) { if (myarray[i].parentcategory_id === namekey) { self.subcategories.push(myarray[i]); } } } search(category, categories); details.push({ firstname: self.subcategories()}); }); self.selectedsubcategory.subscribe(function(subcategory) { function subsearch(namekey, myarray){ (var i=0; < myarray.length; i++) { if (myarray[i].parentcategory_id === namekey) { self.supersubcategories.push(myarray[i]); } } } subsearch(subcategory, categories); details.push({ firstname: self.supersubcategories()}); }); so, variable selectedcategory perform expected , trigger function in self.selectedcategory.subscribe. variable selectedsubcategory not perform expected , instead throw next error - referenceerror: selectedsubcategory not defined. think has using foreach binding within of with binding, i'm not sure. else works expected, , have used add together several objects details array successfully.
any thoughts or clarification needed?
looks wasn't accessing selectedsubcategory in right context. prepending $parents[0]. gave desired results. looks $parents[0].selectedsubcategory. strangely, $parents supposed provide same context $parents[0], doesn't work in case...
javascript data-binding knockout.js referenceerror
No comments:
Post a Comment