You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ember-power-select-with-create首次添加自定义选项失败问题求助

Fix for "Can't call pushObject on undefined" when adding first custom option in ember-power-select-multiple-with-create

Let’s break down exactly what’s going on here and how to fix it:

What’s Causing the Issue

When you add the first custom option, your offer.offer property is likely starting as null or undefined. While you tried to initialize it to an empty array inside your createOffer function, you’re only modifying a local variable—you aren’t updating the actual model property that the component is bound to.

For predefined options, the ember-power-select-multiple-with-create component automatically initializes the selected array under the hood when you pick an option, which is why those work without issues. This automatic initialization doesn’t trigger for custom options added via oncreate, so we need to handle it explicitly.

The cleanest fix is to ensure your model’s offer property starts as an empty array instead of null. This eliminates the initialization problem entirely.

If you’re using modern Ember Data with native classes:

// models/your-model.js (replace with your actual model name)
import Model, { attr } from '@ember-data/model';
import { A } from '@ember/array';

export default class YourModel extends Model {
  @attr('array') offer = A([]); // Initialize as an empty Ember array
}

For older Ember Data syntax:

// models/your-model.js
import DS from 'ember-data';

export default DS.Model.extend({
  offer: DS.attr('array', { defaultValue: () => [] })
});

Solution 2: Update the createOffer Function

If you can’t modify the model initialization, adjust your createOffer function to update the model property directly when initializing the array:

import { A } from '@ember/array';

// ...

createOffer(selected, searchText) {
  // Convert to an Ember array (ensures reactivity and access to pushObject)
  let updatedSelected = A(selected || []);

  if (updatedSelected.includes(searchText)) {
    this.get('notify').alert("Already added!", { closeAfter: 4000 });
  } else {
    updatedSelected.pushObject(searchText);
    // Explicitly save the updated array back to the model
    this.set('offer.offer', updatedSelected);
  }
}

Why This Works

By initializing the model property as an empty array upfront, or explicitly updating the model property in createOffer, you ensure pushObject is always called on a valid array—never undefined. This matches the automatic behavior the component uses for predefined options, making your custom option handling consistent and error-free.

内容的提问来源于stack exchange,提问作者Robin Steiner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:32:20