" FOREACH"循环抛出一个错误

时间:2014-04-22 11:39:11

标签: javascript knockout.js durandal

看起来很简单,但我不明白。所以我有HTML

<div class="ui three column grid" data-bind="foreach: stories">
  <div class="column">
    <div class="ui stacked segment">
        <div class="ui three column grid center aligned">
                <div class="column">
                    <div class="ui buttons icon">
                        <div class="ui button small">
                            <i class="icon plus"></i>
                        </div>
                    </div>
                </div>
                <div class="column">
                    <div class="ui labels circular">
                        <div class="ui label">
                            124124
                        </div>
                    </div>
                </div>
                <div class="column">
                    <div class="ui buttons icon">
                        <div class="ui button small">
                            <i class="icon minus"></i>
                        </div>
                    </div>
                </div>
        </div>
        <div class="ui grid center aligned">
            <div class="row">
                <div class="column">
                    <h1>yo</h1> 
                </div>    
            </div>
            <div class="row">
                <div class="column">
                    <div class="ui segment" data-bind="foreach: {data: stories.strings, as: 'string'}">
                        <p data-bind="text: string"></p>
                    </div>   
                </div>
            </div> 
        </div>
    </div>
  </div>
</div>

我的js文件与viewModel

define(['knockout', 'dataContext'], function (ko, dataContext) {

viewModel = {
    activate: activate,
    main: ko.observable(true),
    stories: ko.observableArray([]),
};

return viewModel;

function activate() {
    return dataContext.getStories().then(function(data) {
        console.log(data.results);
        _.each(data.results, function(result) {
            console.log(result.strings);
            viewModel.stories.push({strings: result.strings});
        });
        console.log(viewModel.stories());
    });
  }
})

所以foreach:&#39;故事&#39;没有用,那就是问题。控制台告诉我

"Unable to process binding "foreach: function (){return stories }"
Message: Unable to process binding "foreach: function (){return {data:stories.strings,as:'string'} }"
Message: stories is not defined;"

1 个答案:

答案 0 :(得分:3)

由于你的第二个foreach

,引发了异常
<div class="ui segment" data-bind="foreach: {data: stories.strings, as: 'string'}">
    <p data-bind="text: string"></p>
</div> 

因为你处于&#34;故事的背景下。编写stories.strings会因为stories项内没有stories属性而抛出,因此您只需要编写strings

<div class="ui segment" data-bind="foreach: { data: strings, as: 'string' }">
    <p data-bind="text: string"></p>
</div>