Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout viewmodel property undefined

Tags:

knockout.js

I have a simple foreach:

<div id="customersArea" data-bind="foreach: people">             <div class="section" data-bind="attr: { 'personid': PersonId }" >                 <div class="sectionActions">                     <div><a class="action" href="#" data-bind='click: $parent.removePerson'>Remove</a></div>                 </div>                 <div class="sectionText">                     <span data-bind="if:LastName, text:LastName"></span>                     <span data-bind="if:FirstName, text:FirstName"></span>                     <span data-bind="if:MailingAddress">                         <span data-bind="with:MailingAddress">                             <span data-bind="text:StreetPartOne"> </span>                             <span data-bind="text:StreetPartTwo">  </span>                             <span data-bind="text:City"></span>                             <span data-bind="text:PostalCode"></span>                         </span>                     </span>                      <span data-bind="if:EmailAddress, text:EmailAddress"></span>                     <span data-bind="if:MainPhoneNumber, text:MainPhoneNumber"></span>                     <span data-bind="if:MobilePhoneNumber, text:MobilePhoneNumber"></span>                  </div>                  <div class="sectionOptions">                  </div>             </div>         </div> 

I am trying to make it such that i can bind against a model {PersonId:33} and the rest will just not render if missing. when i try it this and other ways i get

Uncaught Error: Unable to parse bindings. Message: ReferenceError: MailingAddress is not defined; Bindings value: if:MailingAddress 

I created a simple jsfiddle to test:

http://jsfiddle.net/E7kUr/

like image 400
maxfridbe Avatar asked Feb 14 '12 17:02

maxfridbe


1 Answers

So, there are a few options that you have:

  1. KO will have an issue when you try to bind against undefined properties, unless they are off of an object. So, you can prefix your various bindings with $data. and KO will be able to parse your bindings. Sample: http://jsfiddle.net/rniemeyer/dLCL8/ If you know that several properties will always be together, then you could use a with or if statement around those options.

  2. A different take on handling "undefined" properties is to create a binding that populates these properties when they are missing. Look at this answer. It would be similar, but potentially with the 'text' binding. Sample: http://jsfiddle.net/rniemeyer/dLCL8/4/

like image 55
RP Niemeyer Avatar answered Sep 18 '22 17:09

RP Niemeyer