4

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?

3 Answers 3

3

Use

return {
    Items: items,
    clickSave: addItem
};
Sign up to request clarification or add additional context in comments.

Comments

0

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()
            )
        );
    }
};

Comments

0

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"))
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.