网站首页 >> 牛刀云小程序开发 >> 第2篇 开发模式 >> 页面开发 >> 开发JS

3.3.1.2 自定义JS方法

    在“13.3 实战案例 Hello World”一节中,在输入框组件的值改变事件中,定义了如下的代码,实现格式化输入内容。

   onInputValuechange(event/*{{{*/=this._e.input_valuechange/*}}}*/){

       let hi = "Hello" + event.value;

       this.comp("tableData").setValue("fshuchu", hi);

  }

现在将这个事件改造为调用自定义JS方法来实现,首先添加一个自定义JS方法formatInput,参数value。在这个方法中给value前面加上“Hello:”,再赋值给静态数据集。方法代码如下:

    formatInput(value){

       let hi = "Hello" + value;

       this.comp("tableData").setValue("fshuchu", hi);

    }

将输入框组件值改变事件中的代码,改为调用formatInput方法,并将event.value作为参数,代码如下:

   onInputValuechange(event/*{{{*/=this._e.input_valuechange/*}}}*/){

       this.formatInput(event.value);

   }

需要注意到,在JS中调用自定义JS方法时,前面要加上“this.”。因为formatInputIndexPage类的方法,this默认指向类的实例,在调用类的方法时,要使用实例.方法名()的语法。完整JS代码如下:

import PageImpl from "$UI/wxsys/lib/base/pageImpl";

var app = getApp();

export default class IndexPage extends PageImpl {

constructor(...args){/*{{{*/this.comp = require("_comp").default;

this._e= require("_event_").default;/*代码提示的辅助代码}}}*/

        super(...args);

    }

    onInputValuechange(event/*{{{*/=this._e.input_valuechange/*}}}*/){

       this.formatInput(event.value);

    }

    formatInput(value){

       let hi = "Hello" + value;

       this.comp("tableData").setValue("fshuchu", hi);

    }

}