javascript - 在可观察数组中添加和替换项目的函数

标签 javascript knockout.js

我正在尝试编写一个函数,1. 将一个项目添加到可观察数组中,2. 如果该项目已存在于数组中,则替换该项目

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

我做错了什么?

问候安德斯

最佳答案

这是我的答案:fiddle

在 Chrome 中按 F12 或在 FireFox 中使用 FireBug 查看控制台日志输出。

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);​

关于javascript - 在可观察数组中添加和替换项目的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13020026/

相关文章:

javascript - 获取在字段上拖放的资源的 URL

javascript - createRecord 未定义错误(Firebase + Ember.js)

javascript - JQuery Mobile Listview 滑动菜单

javascript - 有什么方法可以在标准 mvc 表单帖子中包含 knockoutjs 可观察值吗?

javascript - 不要在 IE6 或更低版本中加载脚本

javascript - AngularJS - 如何在按钮单击时获取对象

jquery - 将项目添加到 observableArray 不更新 jQuery 按钮单击上的 View

css - 带 if 的 knockout.js 数据绑定(bind)循环

internet-explorer - 使用 Knockout 绑定(bind)处理 IE 9 和 10 的清除按钮

jquery - knockout 检查装订