【问题标题】:Knockout.js subscribe to observable element inside observable arrayKnockout.js 订阅可观察数组中的可观察元素
【发布时间】:2018-11-26 16:37:06
【问题描述】:

js My Course 在更改时不订阅可观察数组。控制台日志不显示。我不知道如何解决它。有什么想法吗?

class Course {
  constructor(data) {
    this.id = ko.observable(data.id);
    this.name = ko.observable(data.name);
    this.lecturer = ko.observable(data.lecturer);
    this.name.subscribe(function(newName) {
      console.log(newName);
    });
    this.lecturer.subscribe(function(newLecturer) {
      console.log(newLecturer);
    });
  }
}

function ProtoModel() {
  var self = this;
  self.courses = ko.observableArray([]);
  self.addCourse = function() {
    const newCourse = new Course({
      name: this.newCourseNameText(),
      lecturer: this.newCourseLecturerText()
    });
    self.courses.push(ko.mapping.toJS(newCourse));
    self.newCourseNameText("");
    self.newCourseLecturerText("");
  };
}

var model = new ProtoModel();

ko.applyBindings(model);

【问题讨论】:

    标签: knockout.js observable subscribe


    【解决方案1】:

    在 Course 构造函数中,您创建全新的 observable,然后仅将旧 observable 的值分配给它。你订阅了这个新的 observable。

    然后,在创建之后,您会尝试更改“旧”可观察对象,如果您订阅了它的更改 - 您将看到它们。但是,在 newCourse 中创建的 observables 保持不变。

    尝试替换

    self.newCourseNameText("");
    self.newCourseLecturerText("");
    

    self.newCourse.name("");
    self.newCourse.lecturer("");
    

    【讨论】:

    • 我从课程构造函数创建新课程。 newCourseNameText 绑定到干净的输入,当我键入并按下带有 data-bind="click: addCourse" 的按钮时,然后我将此课程推送到可观察数组。最后我在提交后清理了这个输入。但我在表格中有课程数组和输入,当我编辑特定课程时我想订阅它,但它没有用
    • 你能解释清楚吗??我不明白。
    • 您能在更改这些变量的地方添加代码吗?是html还是js?
    • 顺便说一句,当您执行self.courses.push(ko.mapping.toJS(newCourse)); 时,您将推入新课程的可观察数组 json-copy,而不是带有可观察对象的对象。因此,如果您稍后在此数组中编辑某些课程,它不会影响原始订阅,因为它是一个没有可观察对象的不同对象
    猜你喜欢
    • 2012-06-30
    • 2019-12-16
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    • 2018-07-21
    • 1970-01-01
    相关资源
    最近更新 更多