0

Im trying to write a function that 1. adds an item to an observable array and 2. replaces the item if it already exists in the array

self.addNotification = function (name, availability, note) {
    //see if we already have a line for this product
    var matchingItem = self.notifications.indexOf(name);

    if (matchingItem !== undefined) {
        self.notifications.replace(self.notifications()[index(matchingItem)],
            new Notification(self, name, availability, note));
    }
    else {
        self.notifications.push(new Notification(self, name, availability, note));
    }
};

What am I doing wrong?

Regards Anders

2 Answers 2

1

Here is my answer: fiddle

Hit F12 in Chrome or use FireBug in FireFox to see console log output.

var notifications = {
    notifs: [],
    updateNotifications: function(notification) {
        'use strict';

        var matchIndex;

        for (matchIndex = 0; matchIndex < this.notifs.length; matchIndex += 1) {
            if (this.notifs[matchIndex].name === notification.name) {
                break;
            }
        }
        if (matchIndex < this.notifs.length) {
            this.notifs.splice(matchIndex, 1, notification);
        } else {
            this.notifs.push(notification);
        }
    }
};

notifications.updateNotifications({
    name: 'John',
    available: false,
    note: "Huzzah!"
});
notifications.updateNotifications({
    name: 'Jane',
    available: true,
    note: "Shazam!"
});
notifications.updateNotifications({
    name: 'Jack',
    available: true,
    note: "Bonzai!"
});
notifications.updateNotifications({
    name: 'Jane',
    available: false,
    note: "Redone!"
});
console.log(notifications);​
Sign up to request clarification or add additional context in comments.

Comments

1

Well, Array.prototype.indexOf never returns undefined. Its either -1 (not found) or any number starting with 0 for the array index.

1 Comment

Okay thanks, I have changed undefined to -1... But it just keeps adding items to the array.

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.