Sencha Touch - 为啥在我的自定义组件中未定义此功能?

Posted

技术标签:

【中文标题】Sencha Touch - 为啥在我的自定义组件中未定义此功能?【英文标题】:Sencha Touch - Why Is This Function Undefined in my Custom Component?Sencha Touch - 为什么在我的自定义组件中未定义此功能? 【发布时间】:2014-02-12 22:01:17 【问题描述】:

我正在尝试浏览煎茶类系统,但似乎在这方面失败了。

我有一个旋转木马,我也在添加组件。我有一个带有记录的商店,并且我正在遍历记录并在每次迭代中将自定义组件添加到轮播中。这是它的代码......

    var carousel = Ext.create("Ext.Carousel", 
        fullscreen: true
    );

    sights.each(function(sight, index, length)
        carousel.add(Ext.create("Parks.view.ImageView", 
            imageName: sight.get("img"),
            titleName: sight.get("name")
        ));
    );

我的自定义组件具有以下代码,但由于 getImageName() 函数而无法执行。它抱怨它没有定义。但是,根据我对 Sencha 类结构的理解,应该是构造函数在初始化的时候定义的吧?

Ext.define("Parks.view.ImageView", 
  extend: "Ext.Panel",
  fullscreen: true,

config: 
    imageName: "",
    titleName: ""
,

constructor: function(config)
    this.initConfig(config);
,

items: [
    
        xtype: "img",
        layout: "fit",
        src: getImageName()
    
]

);

【问题讨论】:

【参考方案1】:

有一个错误在您的代码中隐藏了另一个错误。

首先,它应该是this.getImageName()。但即使那样它也不会起作用,因为你需要this 指向你的类的一个实例 来调用这个方法(也许你应该阅读一下 javascript 中的范围......这很辣主题!)。

在这里,您必须意识到您的函数将在构造函数之前调用,甚至在Ext.define 之前调用(因为src 属性需要您的方法的返回值您作为参数传递给 Ext.define 的对象的 items 属性中的对象)。

当你需要做一些处理(即执行一个函数)来创建一个组件的配置时,重写它的initialize方法,像这样:

Ext.define("Parks.view.ImageView", 
    extend: "Ext.Panel",
    fullscreen: true,


    config: 
        imageName: "",
        titleName: "",
        layout: "fit"
    ,

// This is not needed, and it will break everything. You're extending from
// a class that already calls initConfig for you. And you don't call the parent
// method, so you're completely removing the component initialization cycle.
//
//    constructor: function(config)
//        this.initConfig(config);
//    ,

    initialize: function() 

        // you should test that you have a value in imageName before using it
        this.add(
            xtype: "img",
            layout: "fit",
            src: this.getImageName()
        );

        // this one is probably not needed because the parent method is empty (it is 
        // is what Ext calls a template method), *but* it is more safe to call it
        // anyway -- in case some override put some code in this method upper in
        // the class hierarchy
        this.callParent(arguments);
    
);

已编辑:我的答案适用于 ExtJS,它不适用于 Touch...

【讨论】:

一旦您将布局添加到面板,就可以使用,就像我在上面编辑过的一样

以上是关于Sencha Touch - 为啥在我的自定义组件中未定义此功能?的主要内容,如果未能解决你的问题,请参考以下文章

是否可以覆盖 Sencha Touch 中特定组件的 SASS 文件?

_Class.scss:Sencha Touch 主题中未定义的变量“$font-family”

如何在我的 Sencha Touch 应用程序中嵌入视频?

app.json Sencha Touch 2.1 中的 buildPaths 似乎已被删除

Sencha Touch - 资源文件的不同路径

选项卡式工具栏内的 Sencha Touch List 组件