如何获得一个自定义ExtJS组件来渲染一些基于绑定值的html

How to get a Custom ExtJS Component to render some html based on a bound value

本文关键字:于绑定 绑定 html 一个 何获得 自定义 ExtJS 组件      更新时间:2023-09-26

我正在尝试获得一个自定义的extjs组件,以基于绑定到它的真/假值来呈现绿色支票或红色x图像。

以前的开发人员已经为呈现自定义标签/自定义按钮编写了一些其他控件,我正试图将这些控件作为控件的基础,但我运气不佳。

我希望能够在如下视图中使用它,其中"recordIsValid"是我的模型中属性的名称。(如果我删除了xtype:它只是呈现为真/假)

{
    "xtype": "booldisplayfield",
    "name": "recordIsValid"
}

这是我目前所掌握的,但ExtJS对我来说相当陌生

Ext.define('MyApp.view.ux.form.BoolDisplayField', {
    extend: 'Ext.Component',
    alias : 'widget.booldisplayfield',
    renderTpl : '<img src="{value}" />',
    autoEl: 'img',
    config: {
        value: ''
    },
    initComponent: function () {
        var me = this;
        me.callParent(arguments);
        this.renderData = {
            value: this.getValue()
        };
    },
    getValue: function () {
        return this.value;
    },
    setValue: function (v) {
        if(v){
            this.value = "/Images/booltrue.png";
        }else{
            this.value = "/Images/boolfalse.png";
        }
        return this;
    }
});

上面的大部分内容我都是从以前的自定义链接按钮实现中获得的。我假设当recordIsValid的模型值绑定到控件时会调用setValue。然后,根据这是真是假,它将用正确的图像覆盖控件的value属性的设置。

然后在initComponent中,它将通过调用getValue来设置renderData value,并将其注入到renderTpl字符串中。

如有任何帮助,我们将不胜感激。

您应该使用tpl选项,而不是renderTpl选项。后者用于呈现组件结构,而不是其内容。这样,您就可以使用update方法来更新组件。

您还需要在组件的构造函数中调用initConfig,以便应用初始状态。

最后,出于语义原因,我建议使用applyValue而不是setValue,并保留getValue/setValue的布尔值。

Ext.define('MyApp.view.ux.form.BoolDisplayField', {
    extend: 'Ext.Component',
    alias : 'widget.booldisplayfield',
    tpl: '<img src="{src}" />',
    config: {
        // I think you should keep the true value in there
        // (in order for setValue/getValue to yield the expected
        // result)
        value: false
    },
    constructor: function(config) {
        // will trigger applyValue
        this.initConfig(config);
        this.callParent(arguments);
    },
    // You can do this in setValue, but since you're using
    // a config option (for value), it is semantically more
    // appropriate to use applyValue. setValue & getValue
    // will be generated anyway.
    applyValue: function(v) {
        if (v) {
            this.update({
                src: "/Images/booltrue.png"
            });
        }else{
            this.update({
                src: "/Images/boolfalse.png"
            });
        }
        return v;
    }
});

这样,您就可以在创建时或以后使用setValue设置您的值。

// Initial value
var c = Ext.create('MyApp.view.ux.form.BoolDisplayField', {
    renderTo: Ext.getBody()
    ,value: false
});
// ... that you can change later
c.setValue(true);

然而,您将无法删除这个组件,因为它处于Ext形式,并将其作为一个成熟的字段。也就是说,它的值不会被设置、检索等。为此,您必须使用Ext.form.field.Field mixin。请参阅另一个问题,了解有关该主题的详细讨论。