2012-12-07 4 views
1

나는 내 부모에게 아이를 추가하려고하는 방법이 있지만 호출이 방법으로 이루어질 때, 호출 부모의 문맥은 정의되지 않습니다.녹아웃 매핑 추가 문제

바이올린 http://jsfiddle.net/poundingCode/THghy/

// Initialized the namespace 
var my = {}; 
    my.models = {}; 

    // View model declaration 
    my.vm = (function (model) { 
     var memberVm = { 
      id: ko.observable(model.Id), 
      company: ko.observable(model.Company), 
      fName: ko.observable(model.FName), 
      lName: ko.observable(model.LName), 
      name: ko.observable(model.Name), 
      positions: ko.observableArray([]), 
      totalPositions: ko.observable(), 
      totalProjects: ko.observable() 
     }; 

     // children 
     memberVm.loadPositions = function (positions) { 
      memberVm.totalPositions = 0; 
      memberVm.totalProjects = 0; 
      $.each(positions, function (i, p) { 
       memberVm.positions.push(new my.models.Position() 
       .company(p.Company) 
       .companyId(p.CompanyId) 
       .description(p.Description) 
       .id(p.Id) 
       .memberId(p.MemberId) 
       .name(p.Name) 
       .title(p.Title) 
       .projects(p.Projects) 
       ); 
       memberVm.totalPositions++; 
       memberVm.totalProjects += p.Projects.length; 
      });// end for each 
     }; //end load positions 

     memberVm.loadPositions(model.Positions); 

     memberVm.fullName = ko.computed(function() { 
      return this.fName() + ' ' + this.lName(); 
     }, memberVm); 


     // Computed observable function. 
     // We append it to the ViewModel here. 

     // return object 
     var vm = { 
      id: memberVm.id, 
      company: memberVm.company, 
      fName: memberVm.fName, 
      fullName: memberVm.fullName, 
      lName: memberVm.lName, 
      name: memberVm.name, 
      positions: memberVm.positions, 
      totalPositions: memberVm.totalPositions, 
      totalProjects: memberVm.totalProjects,  

     }; 
     return vm; 
    }); 

    ///////////////////////////////////// 
    // Add a position - or at least try to! this is where I get into trouble. 

    my.vm.addPosition = (function() { 
     var pos = new my.models.Position(); 
     pos.memberId = my.vm.id; 
     my.vm.positions.push(pos); 
    }); 
    ///////////////////////////////////// 
    // TypeError: my.vm.positions is undefined my.vm.positions.push(pos); 
    my.models.Member = (function() { 
      id = ko.observable(); 
      company = ko.observable(); 
      fName = ko.observable(); 
      lName = ko.observable(); 
      name = ko.observable(); 
      positions = ko.observableArray([]); 

    }); 
    my.models.Position = (function() { 
     this.company = ko.observable();   
     this.id = ko.observable();   
     this.memberId = ko.observable(); 
     this.name = ko.observable(); 
     this.title = ko.observable(); 
     // place holders 
     this.totalProjects = ko.observableArray(); 
     this.totalCredits = ko.observableArray(); 
    }); 


var viewModel = my.vm(data); 
     ko.applyBindings(viewModel); 
my.setUI(); 

HTML을 (명확성을 위해 약칭 함)의 코드

 <script type="text/html" id="positionItemTemplate"> 
      <div class="summary" data-bind="attr : {onClick: 'my.showDetails(' + id() + ')', href: '#detail_'+ id()}"> 
            <a data-bind="attr : { href: '#detail_'+ id()}"> 
            <h2><label data-bind="text: company().Name"></label>: <label data-bind="text: title"></label></h2> </a> 
            <h3><label data-bind="text: title" ></label> <label data-bind="text: startDate" ></label> - <label data-bind="value: endDate" ></label></h3> 

           </div> 
           <div data-bind="attr : {id: 'detail_' + id() }" class="details" style="right: 580px;"> 
            <div class="positionOverview"> 
            <h2><label data-bind="text: company().Name"></label>: <label data-bind="text: title"></label></h2> </a> 
            <a data-bind="attr : {href: '#detail_'+ id()}"> <div class="editor-label"><label>Position</label></div></a> 
             <div class="editor-field"> 
              <input type="text" data-bind="value: company().Name" class="textbox-long"> 
             </div> 
             <div class="editor-label"> 
              <label>Title</label> 
             </div> 
             <div class="editor-field"> 
              <input type="text" data-bind="value: title" class="textbox-long"> 
             </div> 
             <div class="editor-label"> 
              <label>Summary</label> 
             </div> 
             <div class="editor-field"> 
              <textarea data-bind="value: summary" rows="4" cols="60"></textarea> 
             </div> 
             <div class="editor-label"><label>Compensation</label></div> 
             <div class="editor-field"> 
              <select data-bind="options: $parent.compensations, value: compensationId, optionsText: 'Name', optionsValue: 'Id', optionsCaption: 'Select'"></select> 
             </div> 
             <div class="editor-label"><label for="HoursPerWeek" class="hourly">Hours/Week</label></div> 
             <div class="editor-field"> 
              <input type="text" data-bind="value: hoursPerWeek" class="number-short"> 
             </div> 
             <div class="div-table"> 
              <div class="div-table-row"> 
               <div class="div-table-col"><label for="StartDate">Start Date</label></div> 
               <div class="div-table-col"><label for="EndDate">End Date</label></div> 
               <div class="div-table-col"></div> 
              </div> 
              <div class="div-table-row"> 
               <div class="div-table-col"><input type="text" data-bind="value: startDate" class="date"></div> 
               <div class="div-table-col"><input type="text" data-bind="value: endDate" class="date"></div> 

              </div> 
              <div class="div-table-row salary"> 
               <div class="div-table-col"><label for="SalaryStart">$/Hr Start</label></div> 
               <div class="div-table-col"><label for="SalaryStart">$/Hr End</label></div> 
              </div> 
              <div class="div-table-row salary"> 
               <div class="div-table-col"><input type="text" data-bind="value: salaryStart" class="date"></div> 
               <div class="div-table-col"><input type="text" data-bind="value: salaryEnd" class="date"></div> 
              </div> 
             </div> 
             <input id="btnAddProject" type="button" value="Add Project" data-bind="attr : {onClick: 'addProject(new project())'}"> 
             <input type="button" data-bind="attr : {onClick: 'my.showDetails(' + id() + ')'}" value="Update"/> 
            </div>                 
           </div> 
     </script> 
</head> 
    <body> 
     <div id="main"> 
      <div class="marquee center"> 
       <aside class="aside"> 
        <div class="display"> 
        <label data-bind="text: 'Total Positions: ' + totalPositions" ></label><input value="Add Position" type="button" data-bind="attr : {onClick: 'my.vm.addPosition()'}"/><br /> 

        </div> 
        <div class="adPanel"> 
         <h4><div id="message"></div></h4> 
        </div> 
       </aside> 
      </div> 
      <section id="primary" class="primary"> 
       <article id="article1"> 
        <section > 
         <div id="positions"> 
          <div class="position" data-bind="template: { name: 'positionItemTemplate', foreach: positions, as: 'position' }"> 
          </div> 
         </div> 
        </section> 
       </article> 
<!--   <footer class="footer"> 
       <p>Copyright © 2008 All Rights</p> 
      </footer>--> 
     </section> 

     </div> 
    </body> 
</html> 
+0

과 같이 새로운 위치를 추가 할 때 바인딩이 문제가됩니다. 귀하의 바이올린은 붙여 넣은 코드와 다른 것으로 보입니다. 문제가있는 곳은 어디입니까? –

+0

내가 바이올린에 무슨 일이 있었는지 모른다, 나는 곧 다시 게시 할 수 있습니다. 문제는 my.vm.positions을 호출하면 위치가 null이라는 오류가 발생한다는 것입니다. –

+0

는, 사전에 통지 할 당신의 매우 기민한 모습 –

답변

2

주요 문제는 당신의 my.vm 당신이 사용할 수있는 생성자 함수는 점이다 my.vm의 인스턴스를 만듭니다. 그러나, addPosition 기능은 my.vm에 직접 추가 my.vm.positions에 밀어 시도했다.

이상적 싶은 당신의 VM의 인스턴스에 기능을 사용할 수 있도록 해당 인스턴스의 positions 배열에 밀어 것입니다.

그래서 VHM 선언 안에 addPosition을 넣고 돌아 오는 변수 vm에서 작동하게합니다. 이 시점에서 company은 비어 있고 바인딩 중 일부는 company().Name

+0

을 모든 사람들 덕분에, 그래 나는 부모 레코드에서 여러 속성을 그릴 수있을 것 아이를 추가하기 위해 바이올린 노력하고있어 업데이트되었습니다. 나는, 존 파파의 녹아웃 예와 '계시 모델'패턴을 다음은 제안으로 VM 내에서 내 함수 호출을 이동하지만 지금은 VM 페이지에 결합하지 않는했습니다. 재미는 끝나지 않습니다. –

관련 문제