【问题标题】:How to bind polymer template dom-repeat using promise object?如何使用 promise 对象绑定聚合物模板 dom-repeat?
【发布时间】:2018-02-14 22:41:46
【问题描述】:

我尝试使用这个调用firestore的函数绑定下拉值然后我使用promise返回值

HTML

<template is="dom-repeat" items="{{_modOptsArry(item.modKey)}}" as="opt">
     <paper-item value="{{opt.$key}}">{{opt.obj.val}}</paper-item>
</template>

JavaScript

_modOptsArry(modeKey) { 
    let opts = [];
    var promise = new Promise((resolve, reject) => {
        firebase.firestore().collection("record").doc("s1").collection("class").orderBy('o').onSnapshot(function (querySnapshot) {
            // let opts = [];
            querySnapshot.forEach(function (doc) { 
                var model = doc.data(); 
                opts.push({ $key: doc.id, obj: { val: model.nm } });
            });
            resolve(opts); 
        })
    })
    promise.then(function (result) {
        return Promise.resolve(result); // Here i am returning array but in the dom-repeat it not binding values because it is returning Promise Object My Array is there inside this Promise object. how to resolve this problem..
    }); 
}

【问题讨论】:

    标签: javascript promise polymer-1.0 polymer-2.x


    【解决方案1】:

    有一个看起来像这样的函数

    getDropdownItems(props, item) {
        if (!this.props[item])
            this._modOptsArry(item);
        return this.props[item]
    }
    

    让您的_mopOptsArry 方法将结果分配给this.props[item];然后通知对象。像这样:

    this.props[item] = yourResultArray;
    this.notifyPath('props.' + item);
    

    有一个名为props 的属性,其值为{}

    然后在你的html中,而不是调用this._modOptsArry;致电[[getDropdownItems(props.*, item.modkey)]]

    【讨论】:

    • 感谢 Jeremy 的回复,我可以为该属性分配一个值并使用它,但在这里我将 UI 绑定为完全动态的。如果我在所有地方引用相同的属性,我会在 UI 中多次绑定相同的 UI 元素,所有元素都将被此属性值覆盖,这就是我使用返回方法的原因,以便我可以为每个元素绑定唯一值。 .
    • 嗨@RajT,如果编辑中的解决方案有效,请告诉我。
    【解决方案2】:

    像这样改变你的方法:

    _modOptsArry() { 
        let opts = []
        const that = this
        firebase.firestore().collection("record").doc("s1").collection("class").orderBy('o').onSnapshot(function (querySnapshot) {
            querySnapshot.forEach(function (doc) { 
                var model = doc.data()
                opts.push({ $key: doc.id, obj: { val: model.nm } })
            })
            that.set('myArray', opts)
        })
    }
    

    只需将 myArray 绑定到 dom-repeat 模板

    <template is="dom-repeat" items="{{myArray}}" as="opt">
         <paper-item value="{{opt.$key}}">{{opt.obj.val}}</paper-item>
    </template>
    

    【讨论】:

    • 我不能这样做,因为我将这个函数用于一种形式的动态字段我可能会根据元素类型绑定 10 个动态下拉列表,所以我不能使用一个范围来基于 10 个下拉列表关键所有下拉值都会改变,这就是我试图返回的原因..还有一个人也回答了他们,我也发表了同样的评论..
    • 你的表单在什么方面是“动态的”?因为我提供的解决方案适用于我能想到的任何情况,而且它是动态的。你的“物品”取决于什么?
    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多