为什么在ember中未定义.pushObject方法

tzxcd3kk  于 2023-03-08  发布在  其他
关注(0)|答案(1)|浏览(172)

"model. pushObejct不是函数"错误。我正在尝试构建一个待办事项列表app ..,在更新对象时,它说model. pushObject不是函数。

<ul class="hand">
  {{#each @model as |item|}}
  {{#if item.id}}
  <li>{{item.title}}</li>
  <button onclick={{fn this.delete @model item}} type='button'>delete</button>
  {{/if}}
  {{/each}}
</ul>
<form onsubmit={{fn this.submit @model}}>
  <Input placeholder='Add todo' type='text' value={{this.text}} 
    onchange={{fn this.onChange}} />
  <button type='submit'>Add</button>
  {{log @model}}
</form>
@tracked
  text = "";

  @action
  submit(model, event) {
    event.preventDefault();
    const i = model[model.length - 1].id + 1;
    const newTodo = {
      id: i,
      title: this.text
    };
    model.pushObject(newTodo);
    model=model;
    console.log("add", model);
  }

  @action
  onChange(e) {
    this.text = e.target.value;
  }
  @action
  delete(model, item) {
    const index = model
      .map((file, index) => {
        if (file.id === item.id) {
          set(item, "id", null);
          set(item, "title", null);
          return index;
        }
      })
      .filter(id => id !== undefined);
    model.splice(index[0], 1);

我尝试了model. push,它正在工作,但{{# each}}没有更新信息。

@action
  submit(model, event) {
    event.preventDefault();
    const i = model[model.length - 1].id + 1;
    const newTodo = {
      id: i,
      title: this.text
    };
    model.push(newTodo);
    model=model;
    console.log("add", model);
  }

对象被推送但UI未更新:

iszxjhcz

iszxjhcz1#

pushObject在本机JS数组docs here上不存在
要使用pushObject,必须启用原型扩展。下面是相关的docs for enabling/disabling
另一种本地方式是执行this.array = [...this.array],因为这将更新跟踪的 reference(跟踪更新操作于 references,而不是 values
另一种方法是使用React阵列,如下所示:

import { TrackedArray } from 'tracked-built-ins';

// ...
todos = new TrackedArray();

// ...
todos.push({ /* new object */ });

相关问题