获取“$ item未定义”在applyBindings上 [英] Getting "$item is not defined" on applyBindings

查看:124
本文介绍了获取“$ item未定义”在applyBindings上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用knockout来执行一个非常基本的绑定,但是无法从jquery.tmpl访问 $ item 变量。当我应用绑定时,我一直得到 $ item 未定义。

I'm trying to use knockout to do a pretty basic binding but am having trouble accessing the $item variable from jquery.tmpl. I keep getting "$item is not defined" when I apply the bindings.

之前我已经这样做了所以我知道可以做到但我无法弄清楚为什么它在这种情况下不起作用。有趣的是,如果我删除 templateOptions:{parentItem:$ item} ,那么一切都按预期工作。

I've done this before so I know it can be done but I can't figure out why it is not working in this case. What's interesting is if I remove templateOptions:{parentItem: $item}, then everything works as expected.

我已经包含以下文件

<script type="text/javascript" src="Extension/resources/jquery.1.6.1.js"></script>
<script type="text/javascript" src="Extension/resources/jquery.tmpl.js"></script>
<script type="text/javascript" src="Extension/resources/knockout-1.2.1.js"></script>

我的模板和绑定看起来像这样

My template and bindings look like this

<script type="text/html" id="itemTemplate">
    <span data-bind="text:title"></span>
</script>

<div class="filterResults">
        <span  data-bind="text:message"></span>
        # of items: <span data-bind="text:contentItems().length"></span>
        <table cellspacing="0">
            <tr data-bind="template: { name: 'itemTemplate', foreach: contentItems, 
            templateOptions:{parentItem: $item} 
            }"> </tr>
        </table>            
</div>

我使用以下方式进行绑定:

And I do the binding using:

//viewModel contains a contentItems observableArray
ko.applyBindings(viewModel, $('.filterResults')[0]);


推荐答案

好的,看起来我自己可以回答这个问题。问题似乎是我进行数据绑定并试图访问jquery.tmpl变量$ item的部分实际上并没有使用jquery.tmpl

Ok, looks like I can answer this one myself. The problem seems to be that the part where I did the data-bind and was trying to access the jquery.tmpl variable $item is not actually using jquery.tmpl

<tr data-bind="template: { name: 'itemTemplate', foreach: contentItems, 
        templateOptions:{parentItem: $item} 
        }"> </tr>

这不在模板中,因此没有$ item变量可供访问。 $ item与jquery.tmpl相关联,而不是knockoutjs。我解决这个问题的方法就是把我的视图模型放在那里。

That is not inside a template so there is no $item variable to access. $item is associated with jquery.tmpl, not knockoutjs. The way I got around the issue was to just put my view model in there instead.

<tr data-bind="template: { name: 'itemTemplate', foreach: contentItems, 
        templateOptions:{parentItem: viewModel} 
        }"> </tr>

在实际的模板中,(本例中为itemTemplate),我可以访问$ item变量。

And in the actual templates, (itemTemplate in this example), I can access the $item variable.

这篇关于获取“$ item未定义”在applyBindings上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆