2

我想使用與MVC3 knockout.js「刪除」,我不斷收到錯誤:遺漏的類型錯誤:無法調用方法的不確定

Uncaught TypeError: Cannot call method 'remove' of undefined

的設置是,我有一個UL列表我需要添加到並刪除:

<ul data-bind="foreach: Interviewees"> 
    <li> 
     <div> 
      <a data-bind="click: $root.removeInterviewee" class="xOut"></a> 
     </div> 
     <div> 
      <h2> 
       <span data-bind="text: FirstName"></span> 
       <span data-bind="text: LastName"></span> 
      </h2> 
     </div> 
    </li> 
</ul> 

這裏是JavaScript部分具有淘汰賽的東西:

function SomeThingee(Id, SomeThingeeId, firstName, lastName, title, email) { 
     this.Id = Id; 
     this.SomeThingeeId = SomeThingeeId; 
     this.FirstName = firstName; 
     this.LastName = lastName; 
     this.Title = title; 
     this.Email = email; 
    } 

    var viewModel = ko.validatedObservable({ 
     addSomeThingee: function() { 
      if (!viewModel.isValid()) { 
       viewModel.errors.showAllMessages(); 
       return false; 
      } else { 
       var newSomeThingee = new SomeThingee(this.Id(), 0, this.FirstName(), this.LastName(), this.Title(), this.Email()); 

       $.ajax({ 
        url: '@Url.Action("AddSomeThingee")', 
        type: "POST", 
        data: ko.toJSON(newSomeThingee), 
        dataType: "json", 
        contentType: "application/json; charset=utf-8", 
        success: function (result) { 
         newSomeThingee.SomeThingeeId = result.message; 
        }, 
        error: function (result) { 

        } 
       }); 

        this.SomeThingees.push(newSomeThingee); 
       } 
     }, 
     removeSomeThingee: function (item) { 
      this.SomeThingees.remove(item); 
     } 
    }); 

    $(function() { 
     var jsonModel = '@Html.Raw(JsonConvert.SerializeObject(this.Model))'; 
     var mvcModel = ko.mapping.fromJSON(jsonModel); 

     var myViewModel = new viewModel(); 
     var g = ko.mapping.fromJS(myViewModel, mvcModel); 

     ko.applyBindings(g, document.getElementById("someDiv")); 

    }); 

錯誤OCC urs在這條線上:

this.SomeThingees.remove(item); 

注意SomeThingees集合是從模型本身提供的。 add方法工作得很好,但remove方法不起作用,並給我上面列出的錯誤。我究竟做錯了什麼?

+0

正確的答案可以在這裏找到: http://stackoverflow.com/questions/11398647/knockoutjs-how-do-i-remove-an-item-from-a-child-排列 – jmogera

回答

5

的問題是,當click結合呼叫$root.removeIntervieweethis被設置爲數據項($data)而不是視圖模型($root)。有幾種方法可以解決這個問題。可能最簡單的方法是在綁定中使用函數引用bind

<a data-bind="click: $root.removeInterviewee.bind($root)" class="xOut"></a> 

另請參閱此Github issue作進一步討論。

0

我有同樣的問題,問題是綁定調用設置爲數據項($數據)而不是視圖模型($ root)。我改變了<button data-bind="click: $root.(your delete function).bind($root)"></button>併爲我工作!感謝麥可思

相關問題