1
我試圖實現的是實例化多個視圖模型(數字是變量),但點擊時的函數綁定隻影響最後一個實例,無論從哪裏點擊。Knockout viewmodel函數隻影響最後一個實例
JS
function Photo(name){
var self = this;
self.name = name;
}
function SectionPhotosViewModel() {
var self = this;
// Editable data
self.photos = ko.observableArray([
{
name: 'smth'
},
{
name: 'smth else'
}
]);
// Operations
self.addPhoto = function() {
self.photos.push(new Photo('anything'));
}
}
function bindSectionPhotos(element, index, list){
ko.applyBindings(SectionPhotosViewModel, element);
}
_.each(document.querySelectorAll('fieldset.room'), bindSectionPhotos)
HTML
<fieldset class="room">
<div data-bind="click: addPhoto;" class="btn btn-success">Add new</div>
<ul data-bind="foreach: photos">
<li data-bind="text: name"></div>
</ul>
</fieldset>
<fieldset class="room">
<div data-bind="click: addPhoto;" class="btn btn-success">Add new</div>
<ul data-bind="foreach: photos">
<li data-bind="text: name"></div>
</ul>
</fieldset>
<fieldset class="room">
<div data-bind="click: addPhoto;" class="btn btn-success">Add new</div>
<ul data-bind="foreach: photos">
<li data-bind="text: name"></div>
</ul>
</fieldset>
<fieldset class="room">
<div data-bind="click: addPhoto;" class="btn btn-success">Add new</div>
<ul data-bind="foreach: photos">
<li data-bind="text: name"></div>
</ul>
</fieldset>
而且不管按鈕我點擊,只有最後intance被修改。 Ideeas?建議?
教訓教訓。謝謝! –