EmberJS/HandlebarsJS 的自定义 for 循环助手 [英] Custom for-loop helper for EmberJS/HandlebarsJS

查看:26
本文介绍了EmberJS/HandlebarsJS 的自定义 for 循环助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两小时前我开始:嵌套 HandlebarsJS #each helpersEmberJS 不工作

在我自己想出一个可接受的临时解决方案后不久,问题仍未得到解答.我的问题还不止于此.

Shortly after I figured an acceptable temporary solution myself, question is still unaswered. My problems didn't stop there though.

我现在正在尝试制作一个自定义帮助程序,它将循环遍历对象数组,但排除第一个索引 - 几乎:for(i = 1; i < length; i++) {}.我在网站上读过你必须获得上下文的长度并将其传递给选项 - 考虑到你的函数看起来像:forLoop(context, options).

I am now trying to make a custom helper which will loop through an array of objects, but exclude the first index - pretty much: for(i = 1; i < length; i++) {}. I've read on websites you have to get the length of your context and pass it to options - considering your function looks like: forLoop(context, options).

然而,上下文是一个字符串而不是一个实际的对象.当你做一个.length 时,你会得到字符串的长度,而不是数组的大小.当我将它传递给选项时,什么也没有发生 - 更不用说浏览器冻结了.

However, context is a string rather than an actual object. When you do a .length, you will get the length of the string, rather than the size of the array. When I pass that to options, nothing happens - not too mention browser freezes.

然后我首先尝试在将 getPath 传递给选项之前执行它,这将返回一个空字符串.

I then first tried to do a getPath before passing it to options, this returns an empty string.

我应该怎么做,我之前只为 HandlebarsJS 编写了 for 循环代码并且有效,但 EmberJS 似乎不接受,为什么?

What am I supposed to do instead, I made the for-loop code before for just HandlebarsJS and that worked, but EmberJS doesn't seem to take it, why?

我几乎也跟着:http://handlebarsjs.com/block_helpers.html-> 简单的迭代器

I pretty much also followed: http://handlebarsjs.com/block_helpers.html -> Simple Iterators

推荐答案

我自己试了很久才解决的.

I solved this myself after trying for a long time.

HandlebarsJS 方法(如网站上所述)对 EmberJS 不再有效,现在如下所示:

The HandlebarsJS method (as described on the site) is no longer valid for EmberJS, it's now as follows:

function forLoop(context, options) {
    var object = Ember.getPath(options.contexts[0], context);
    var startIndex = options.hash.start || 0;

    for(i = startIndex; i < object.length; i++) {
        options(object[i]);
    }
}

哎呀,您甚至可以扩展 for 循环以包含索引值!

Heck, you could even extend the for-loop to include an index-value!

function forLoop(context, options) {
    var object = Ember.getPath(options.contexts[0], context);
    var startIndex = options.hash.start || 0;

    for(i = startIndex; i < object.length; i++) {
        object[i].index = i;

        options(object[i]);
    }
}

这是一个带有可变起始索引的工作循环.您可以像这样在模板中使用它:

This is a working for-loop with variable start index. You use it in your templates like so:

{{#for anArray start=1}}
    <p>Item #{{unbound index}}</p>
{{/for}}

这篇关于EmberJS/HandlebarsJS 的自定义 for 循环助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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