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

如何在Knockout.js外部访问foreach绑定的ObservableArray?

Accessing a Knockout.js ObservableArray from Outside a foreach Binding

Got it, let's tackle this problem head-on. The core frustration here is that ko.dataFor() and ko.contextFor() return the context of individual items when called on elements inside a foreach loop, not the parent array itself. Below are two practical, reliable solutions tailored to your nested, dynamic view model scenario:


Solution 1: Access the Array via the Parent Binding Context

Since your foreach is attached to the .selectedArticles container div, you can target that element to get the parent data context that holds your articles array. Here's how:

Step-by-Step Implementation

  1. Grab the container element that has the foreach binding:
    const selectedArticlesContainer = document.querySelector('.selectedArticles');
    
  2. Get the parent data context for this container (this will be the deep.nested.shit observable object from your view model):
    const parentContext = ko.dataFor(selectedArticlesContainer);
    
  3. Access the full ObservableArray:
    const articlesArray = parentContext.articles(); // Returns the raw array of article items
    

Use Case Example (Filtering Lookup Data)

Once you have the array, you can extract values and filter your lookup data as needed:

// Extract all selected key values from the articles array
const selectedKeys = articlesArray.map(item => item.key());

// Get the full lookup dataset from your view model
const fullLookup = VM.some.lookup();

// Filter lookup items that aren't already in the articles array
const availableItems = fullLookup.filter(item => !selectedKeys.includes(item.key()));

// Send data to server via AJAX
fetch('/your-endpoint', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ selectedKeys, availableItems })
})
.then(res => res.json())
.then(serverResponse => {
  // Handle server response here
})
.catch(err => console.error('Request failed:', err));

Solution 2: Create a Custom Binding to Expose the Array

If your view model structure is dynamic and you don't want to rely on hardcoding parent paths, a custom binding can store a direct reference to the ObservableArray on the DOM element. This is especially useful for deeply nested or variable arrays.

Step-by-Step Implementation

  1. Define the custom binding:
    ko.bindingHandlers.foreachWithArrayRef = {
      init: function(element, valueAccessor) {
        // Store the ObservableArray reference on the DOM element
        element._koBoundArray = valueAccessor();
        // Delegate to Knockout's native foreach binding
        return ko.bindingHandlers.foreach.init.apply(this, arguments);
      },
      update: function(element, valueAccessor) {
        // Update the reference if the array changes
        element._koBoundArray = valueAccessor();
        return ko.bindingHandlers.foreach.update.apply(this, arguments);
      }
    };
    
  2. Update your HTML to use the custom binding:
    <div data-bind="foreach: some.super">
      <div class="selectedArticles" data-bind="foreachWithArrayRef: deep.nested.shit.articles">
        <div data-bind="text: key() + ' - ' + value()"></div>
      </div>
    </div>
    
  3. Access the array directly from the DOM element:
    const selectedArticlesContainer = document.querySelector('.selectedArticles');
    const articlesArray = selectedArticlesContainer._koBoundArray(); // Get the full array
    

Key Notes

  • The first solution works best if you know the consistent property name of the array within its parent context.
  • The second solution is more flexible for dynamic or deeply nested models where the array's path might change.
  • Always remember: if you call ko.dataFor() on an element inside the foreach loop (like the text display div), you'll get the individual item context—you need to target the container element with the foreach binding to get access to the array's parent context.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:10:02