当前位置: > > > Rivets.js - 实现rv-on-[event]事件的自定义参数传递(以onclick事件为例)

Rivets.js - 实现rv-on-[event]事件的自定义参数传递(以onclick事件为例)

我们知道使用 Rivets.js 时,通过 rv-on-[event] 可以将各种回调函数绑定到元素相应的监听事件上。比如 rv-on-click 便是绑定鼠标点击时间。
默认情况下,当事件触发时,事件处理函数会接收到两个参数:
  • 第一个参数是事件本身(单击等)
  • 第二个参数是模型上下文
但有时光有这两个参数可能还不够,下面介绍如何将自定义参数传递给事件处理程序。

一、修改 Rivets 默认配置

首先我们要修改默认的事件处理配置,增加自定义参数的相关功能。配置完毕后,只要事件对象上有"data-on-[event]"属性,便会将该属性值作为自定义参数进行传递。
Rivets.configure({
    // on-事件增加参数传递
    handler: function (context, ev, binding) {
        //获取 data-on-[event] 属性数据,并作为自定义参数
        var eventType = binding.args[0];
        var arg = context.getAttribute('data-on-' + eventType);

        //如果有自定义参数的话,则在原来的基础上增加这个参数的传递
        if (arg) {
            //如果有逗号则自动拆成参数数组
            var args = arg.split(",");
            if(args.length>1){
              this.call(context,ev, binding.view.models, args);
            }else{
              this.call(context,ev, binding.view.models, arg);
            }
        } else {
            //如果没有自定义参数,还是原来的逻辑
            return this.call(context, ev, binding.view.models);
        }
    }
});

二、传递自定义参数的样例

1,通过 data-on-[event] 属性传递自定义参数

(1)js 代码
//数据模型
var item = {
  name : "点击",
  showInfo : showInfo
}

//按钮点击响应方法
function showInfo(e, model, arg) {
  console.log(e);
  console.log(model);
  alert(arg);
}

//绑定并显示模型
rivets.bind($("#detail"), {
  item: item
});

(2)html 页面代码
<section id="detail">
  <button rv-on-click="item.showInfo" data-on-click="我是自定义参数">
    { item.name }
  </button>
</section>

(3)点击按钮,运行结果如下:

2,想要传递多个自定参数,可以用逗号隔开

(1)js 代码
//数据模型
var item = {
  name : "点击",
  showInfo : showInfo
}

//按钮点击响应方法
function showInfo(e, model, args) {
  console.log(e);
  console.log(model);
  alert(args[0]+"\n"+args[1]);
}

//绑定并显示模型
rivets.bind($("#detail"), {
  item: item
});

(2)html 页面代码
<section id="detail">
  <button rv-on-click="item.showInfo" data-on-click="自定义参数1,自定义参数2">
    { item.name }
  </button>
</section>

(3)点击按钮,运行结果如下:

3,也可以使用绑定的模型值作为自定义参数

(1)js 代码
//数据模型
var item = {
  name : "点击",
  info: "欢迎访问 hangge.com",
  showInfo : showInfo
}

//按钮点击响应方法
function showInfo(e, model, arg) {
  console.log(e);
  console.log(model);
  alert(arg);
}

//绑定并显示模型
rivets.bind($("#detail"), {
  item: item
});

(2)html 页面代码
<section id="detail">
  <button rv-on-click="item.showInfo" rv-data-on-click="item.info">
    { item.name }
  </button>
</section>

(3)点击按钮,运行结果如下:
评论0