2015-11-04 50 views
0

我有很糟糕的時間搞清楚如何通過功能中的指定model(說click函數)。是否可以在點擊功能中傳遞特定模型?

我有這個模型。

的JavaScript

var Bar = function() { 
    this.id = ko.observable(); 
    this.name = ko.observable(); 
    this.barItems = ko.observableArray([]); 
}; 

var BarItem = function() { 
    this.id = ko.observable(); 
    this.type = ko.observable(); 
}; 

var addBarItem = function(item) { 
    // seems that the "item" here is the whole viewmodel 
}; 

var bars = ko.observableArray([]); // the elements here are Bar objects 
var selectedBar = ko.observable(); // passed a Bar object 

HTML

<div data-bind="with: selectedBar"> 
    <p data-bind="text: name></p> 
    <div> 
    <input type="text" data-bind="value: type" /> 
    <button data-bind="click: $root.addBarItem">Add Bar Item</button> 
    </div> 
</div> 

一旦我點擊了添加欄項目,它是獲得Bar對象。我如何通過BarItem

任何幫助將不勝感激。謝謝

+0

你檢查過的文檔:http://knockoutjs.com/documentation/click-binding.html#note-2-accessing-the-event-object-or-passing-more-parameters? – nemesv

+0

你實際上沒有展示你的*模型*,你只是展示了一些你賦予某些變量的函數。 – connexo

+0

@connexo嗨,我有一個完整的運行代碼在這裏http://stackoverflow.com/questions/33518437/how-to-push-object-to-an-observablearray請看看。 –

回答

1

將您需要的任何東西集成到您的視圖模型中。以此爲起點。

var BarViewModel = function() { 
    var self = this; 

    self.Bar = { 
     id: ko.observable(), 
     name: ko.observable(), 
     barItems: ko.observableArray([]) 
    }; 

    self.BarItem = { 
     id: ko.observable(), 
     type: ko.observable() 
    }; 

    self.addBarItem = function(item) { 
     // when referenced within foreach will receive the current item automatically 
    }; 

    self.bars = ko.observableArray([]); // the elements here will be Bar objects 
    self.selectedBar = ko.observable(); // passed a Bar object 
}; 

ko.applyBindings(new BarViewModel()); 
+0

哦,好吧。所以我可以像...'

..fields here..
'? –

相關問題