Reputation: 2544
I have a problem with loading an element into my items Observable-Array - with an event.
ViewModel = (function () {
var
items = ko.observableArray([]),
removeItems = function (element) {
items.remove(element);
},
saveAll = function () {
return ko.toJS(items);
},
addItem = function (element) {
items.push(element);
return false; // no Page-Reload after button-klick
};
return {
Items: items,
// i call addItem with a dummy object (for testing)
clickSave: addItem(new Customer(1, "Tfsd", "Tfsd"))
};
})();
(fiddle)
Why is the addItem function called, without even clicking the button? is it because of the () at the end of the function?
addItem = function (element) {
items.push(element);
return false; // no Page-Reload after button-click
};
what can i do to make this for the event only? Or is my problem somewhere else?
Upvotes: 4
Views: 5620
Reputation: 4165
This should work if you want the new item to be created always the same.
return {
Items: items,
clickSave: addItem.bind(null, new Customer(1, "Tfsd", "Tfsd"))
};
Upvotes: 0
Reputation: 338118
Why is the addItem function called, without even clicking the button? is it because of the () at the end of the function?
Yes.
Do this instead:
return {
Items: items,
clickSave: function() {
addItem(
new Customer(
items().length + 1, // or whatever you use to determine new IDs
$("#inputVorname").val(),
$("#inputNachname").val()
)
);
}
};
Upvotes: 0