2012-08-31 26 views
1

我试图创建自定义属性值对象的属性值(基于函数的条件)对我的分机的对象,而不是仅指定一个值。的Ext JS 4:自定义基于条件

实施例1:

旧代码(工作)

 this.buttons = [ 
      { 
       text: 'Save', 

enter image description here

新代码(不工作)

 this.buttons = [ 
      { 
       text: function() { 
        return 'Save X'; 
       }, 

enter image description here

实施例2:

旧代码(工作)

    }, { 
         width: 270, 
         labelAlign: 'right', 
         xtype: 'textfield', 
         name: 'user_id', 
         fieldLabel: 'User ID', 
         hidden: true 
        }] 

新代码(不工作)

    }, { 
         width: 270, 
         labelAlign: 'right', 
         xtype: 'textfield', 
         name: 'user_id', 
         fieldLabel: 'User ID', 
         hidden: function() { return true; } 
        }] 

例3:

忽略整个文本框对象(例如懒惰)完全基于一个条件:

    }, { 
         width: 270, 
         labelAlign: 'right', 
         xtype: 'textfield', 
         name: 'employee_number', 
         fieldLabel: 'Employee Number' 
        }] 

回答

4

你根本无法做到这样。用函数替换类型是不可能的。在你的情况下,你将一个函数引用分配给一个预期为布尔值的变量,对于该字符串也是一样的。

解决方案A.

,您应考虑自己写一个场厂。在该工厂中,您可以在分配配置之前执行任何功能。 (排序相同,则B,而可以被用于减少函数调用的)

溶液B.

使用函数引用本身。然后这个应该被执行。 (不需要类延伸并且可以重复使用)

// The data store containing the list of states 
var states = Ext.create('Ext.data.Store', { 
    fields: ['abbr', 'name'], 
    data : [ 
     {"abbr":"AL", "name":"Alabama"}, 
     {"abbr":"AK", "name":"Alaska"}, 
     {"abbr":"AZ", "name":"Arizona"} 
     //... 
    ] 
}); 
Ext.namespace('my.util.helper'); 
my.util.helper.decideHide = function() { return true; } 

// Create the combo box, attached to the states data store 
Ext.create('Ext.container.Container', { 
    renderTo: Ext.getBody(), 
    items: [{ 
     xtype: 'combo', 
     fieldLabel: 'Choose State', 
     store: states, 
     queryMode: 'local', 
     displayField: 'name', 
     valueField: 'abbr', 
     test: my.util.helper.decideHide(), 
     listeners: { 
      afterrender: function(n) { 
       alert(n.test); 
      } 
     } 
    }] 
}); 

解决方案C.

如果else语句

// ... // more code 
{ 
    text: myCondition ? 'Text A' : 'Text B', 
    // more code 
} 
// ... // more code 
+0

解决方案A是矫枉过正imo。解决方案B目前不会按照其编码工作。 'decideHide'是一个永远不会执行的函数。解决方案C不使用功能。 – pllee

+0

我必须承认,如果解决方案B希望在没有全球范围的情况下以这种方式工作,那么您完全正确 – sra

+0

谈论解决方案C:如果可能的话,应该避免任何不需要的函数调用。这是循环内最重要的,但如果我只检查一个条件,则不需要为此调用函数。应用程序越大,这些小东西就越有助于保持性能。 – sra

0

是啊,这是行不通的我在这种情况下,大多数使用该解决方案被简化,一些分机CONFIGS采取将被评估的功能,但大部分别吨。而不是创建匿名函数,而不是调用它们,我会做这样的事情:

Ext.define('UserPanel', { 
    extend : 'Ext.panel.Panel', 
    initComponent : function() { 

     this.items = [{ 
      xtype : 'button', 
      text : this._getSaveButtonText() 
     }, { 
      width : 270, 
      labelAlign : 'right', 
      xtype : 'textfield', 
      name : 'user_id', 
      fieldLabel : 'User ID', 
      hidden : this._isUserIdHidden() 
     }] 
     this.callParent(); 
    }, 

    _getSaveButtonText : function() { 
     return 'Save'; 
    }, 

    _isUserIdHidden : function() { 
     return true; 
    } 
});