knockoutjs调用一直执行,我怎么只能调用一次?

问题描述 投票:1回答:1

我有这段代码:

t._teacherOptions = ko.observable();

function getTeacherList() {
  $.ajax({
    type: "POST",
    url: "/webservices/Service.asmx/GetTeachers",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(i) {
      if (i.d) {
        console.log(i.d);
        return t._teacherOptions(i.d);

      }
    },
    error: function(n) {
      u(n);
    }
  });
}

t.TeacherOptions = ko.computed(function() {
  getTeacherList();
  return t._teacherOptions();
});

然后是我的html:

<select data-bind="options: $root.TeacherOptions(), value: Id, optionsText: 'Name'"></select>

由于某种原因,当打开页面时,获取教师列表的功能不断循环而不停。

我能够获得所需的结果,但是循环不断进行,我需要停止该过程。我在这里做错什么了吗?

javascript knockout.js knockout-2.0 knockout-3.0
1个回答
1
投票

您循环不断,因为您的TeacherOptions(是computed)访问了_teacherOptions(因此创建了依赖项),并且因为您正在更改_teacherOptions回调中的success的值Ajax调用,TeacherOptions再次被评估(因为它取决于_teacherOptions),并再次发出Ajax请求。

尝试在getTeacherList()之外呼叫computed

t._teacherOptions = ko.observable();

function getTeacherList() {
  $.ajax({
    type: "POST",
    url: "/webservices/Service.asmx/GetTeachers",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(i) {
      if (i.d) {
        console.log(i.d);
        return t._teacherOptions(i.d);

      }
    },
    error: function(n) {
      u(n);
    }
  });
}

getTeacherList();

t.TeacherOptions = ko.computed(function() {
  return t._teacherOptions();
});

请参见Documentation

© www.soinside.com 2019 - 2024. All rights reserved.