道场:如何提升dijit?

时间:2017-01-19 16:29:59

标签: javascript dojo dijit.form

是否可以通过编程方式将某个行为绑定到dijit?

即。假设我在整个项目中使用了这个dijit / form / NumberSpinner。现在我希望所有NumberSpinners都有一个onFocus: function() { console.log('hi') }

通常我会这样做:

          … new NumberSpinner({
                onFocus: function() { console.log('hi'); },
                …
            });

关于每个元素。有没有办法将此绑定为每个NumberSpinner实例的默认行为??

由于

2 个答案:

答案 0 :(得分:1)

我终于找到了如何做到这一点。

使用Extend

像这样:

lang.extend(NumberSpinner, {
    _onFocus: function() { console.log('hi'); }
});

JSBIN上的工作示例:https://jsbin.com/sesotolove/2/edit?html,output

参考:https://dojotoolkit.org/reference-guide/1.7/dojo/extend.html

使用Prototype

只需覆盖原型就可以实现同样的目标:

NumberSpinner.prototype._onFocus: function() { console.log('hi'); }

答案 1 :(得分:1)

一个选项是创建自己的自定义组件,从NumberSpinner扩展并覆盖/添加所需的所有功能和属性。

示例:

应用程序/ CustomNumberSpinner.js

define([
  'dojo/_base/declare', 
  'dijit/form/NumberSpinner'
], function(
  declare,
  NumberSpinner
) {

  // The declare and the references passed in the array on the next line defines what you are extending
  return declare([NumberSpinner], {

    /* Add all functions/props that you want in this object */

    onFocus: function() {
      console.log('Hi, this is a onFocus event being handled');
    }      

  });

});

对自定义组件进行编码后,您只需要将模块导入到您想要使用它的位置并像使用默认的NumberSpinner一样实例化它,但是您不需要传递道具/函数你需要在构造函数args)。

相关问题