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?
Use
return {
Items: items,
clickSave: addItem
};
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()
)
);
}
};
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"))
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.