2012-08-29 65 views
1

我從服務器中獲取一個對象數組,我想要添加一個方法。在下面的示例中,我希望它被稱爲doAlert。當我嘗試使用data-bind =「click:doAlert」敲除時綁定到doAlert時,拋出異常。我懷疑我添加了錯誤的功能,所以任何建議將不勝感激。由於如何將函數添加到映射對象?

$(document).ready(function() { 
    var url = GetUrl(); 
    $.getJSON(url, function (data) { 

     var mapping = { 
      doAlert: function (options) { 
       alert('test');  
      } 
     } 

     var viewModel = ko.mapping.fromJS(data, mapping); 
     ko.applyBindings(viewModel); 
    }); 
}); 


<ul data-bind="foreach: $data"> 
<li> 
    <span data-bind="text: Title"></span> 
    <div class="btn-group" style="display:inline"> 
     <a class="btn-small btn dropdown-toggle" data-toggle="dropdown" href="#">Action 
        <span class="caret"></span> 
     </a> 
     <ul class="dropdown-menu"> 
      <a data-bind="click: doAlert"><li>Edit</li></a> 
      <a><li>Delete</li></a> 
     </ul> 
    </div> 
</li> 

回答

2

結帳這個JsFiddle Demo

我更改演示您的視圖模型點點,但您的HTML保持不變。

您需要在映射中定義一個create函數。

// Fake Data for demonstration 
var fakeData = [{ 
    "id": 1, 
    "Title": "C++"}, 
{ 
    "id": 2, 
    "Title": "Java"}, 
{ 
    "id": 3, 
    "Title": "JavaScript"}, 
{ 
    "id": 4, 
    "Title": "Scala"}, 
{ 
    "id": 5, 
    "Title": "Python"} 
]; 


function Model() { 

var self = this; 

// You are using foreach syntax so we need to define an observableArray 
this.dataArray = ko.observableArray([]); 

this.loadData = function() { 
    $.ajax({ 
     type: 'POST', 
     url: '/echo/json/', 
     data: { 
      json: ko.toJSON(fakeData) 
     }, 
     success: function(data) { 

      var mapping = { 

       create: function(options) {     
        options.data.doAlert = function() { 
         alert(options.data.Title); 
        } 
        return options.data; 
       } 
      } 
      // Map returning object into the our dataArray 
      ko.mapping.fromJS(data, mapping, self.dataArray); 
     }, 
     dataType: 'json' 
    }); 
} 
} 
}; 

var viewModel = new Model(); 
ko.applyBindings(viewModel); 
viewModel.loadData();​ 

傳遞給create函數的選項參數有一些屬性。我們可以通過options.data屬性來訪問我們的數據。在mapping documentation

簽出有關選項參數的更多信息