【问题标题】:Bind observable array using AJAX inside function在函数内部使用 AJAX 绑定可观察数组
【发布时间】:2015-11-30 15:21:30
【问题描述】:

我正在使用 Knockout.js。我有这样的功能:

function deviceGroupItem(item) {
    this.DeviceGroupName = item.DeviceGroupName;
    this.groupDevicesVisible = ko.observable(false)
    this.groupDevicesArray = ko.observableArray();
    this.deviceGroupClick = function () {
        if (this.groupDevicesVisible() == false) {
            this.groupDevicesVisible(true)
            $.ajax({
                url: returnServer() + '/api/Mobile/getRoomDevices?accessToken=' + localStorage.getItem('Token'),
                type: "GET",
                dataType: "json",
                success: function (data) {
                    this.groupDevicesArray()($.map(data, function (item) {
                        return new roomDeviceItem(item);
                    }))
                },
                error: function () {

                }
            })
        } else {
            this.groupDevicesVisible(false)
        }
    }
    return this;
}

问题是,当我尝试绑定时:

this.groupDevicesArray = ko.observableArray();

使用:

this.groupDevicesArray()($.map(data, function (item) {
                        return new roomDeviceItem(item);
                    }))

我收到错误“this.groupDevicesArray 不是函数”。老实说,我不知道如何以正确的方式做到这一点。你知道我怎样才能做到这一点吗?

【问题讨论】:

  • 试试这个:this.groupDevicesArray (ko.utils.arrayMap(data, function(item) { return new roomDeviceItem(item); }); 或 this.groupDevicesArray($.map(data, function (item) { return new roomDeviceItem(item); }))
  • 谢谢你的回答,但还是一样。

标签: javascript knockout.js knockout-mapping-plugin


【解决方案1】:

问题是因为您在函数 deviceGroupClick 中引用了带有 this 的 observable Array,因为 this 指的是当前上下文,所以该函数不存在。

This 技术依赖于当前闭包,它是一个伪变量 这可能会因范围而异。

视图模型:

function roomDeviceItem(data) {
    this.room = ko.observable(data.room)
}

function deviceGroupItem() {
    var self=this; //Assign this to self & use self everywhere
    self.groupDevicesArray = ko.observableArray();
    self.deviceGroupClick = function () {
        $.ajax({
            url: '/echo/json/',
            type: "GET",
            dataType: "json",
            success: function (data) {
                data = [{
                    'room': 'One'
                }, {
                    'room': 'Two'
                }]
                self.groupDevicesArray($.map(data, function (item) {
                    return new roomDeviceItem(item);
                }))
            }
        });
    };
};
ko.applyBindings(new deviceGroupItem());

工作示例here

以防万一,如果您正在寻找this 的解决方案,您需要使用bind(this) 来获取外部封闭检查的参考here

【讨论】:

  • 我找到了解决方案,但这也有效,感谢您的帮助!
【解决方案2】:

试试

this.groupDevicesArray($.map(data, function (item) {
  return new roomDeviceItem(item);
}));

groupDevicesArray 是 observableArray,$.map 返回一个数组。

【讨论】:

  • 谢谢你的回答,但问题还是一样。
  • jsfiddle 会有所帮助。
猜你喜欢
  • 2014-03-02
  • 2017-07-26
  • 2017-11-25
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多