js:当按钮被点击时,调用一个带有数据绑定参数的函数

Rivets.js: When button is clicked, call a function with an argument from a data binding

本文关键字:一个 数据绑定 函数 参数 按钮 调用 js      更新时间:2023-09-26

这太让人生气了。看起来应该这么简单,但是我找不到魔法咒语。

下面是我需要做的要点:

<div rv-each-thing="data.things">
  <input type=button value="Click" onclick="abc( {thing} )">
</div>

这应该说明我需要做什么。

下面是铆钉网站事件处理程序的默认配置:

 // Augment the event handler of the on-* binder
 handler: function(target, event, binding) {
    this.call(target, event, binding.view.models)
 }

因此,除了事件对象之外,您还可以作为第二个参数获得与特定绑定相关的模型的引用。

使用which可以访问特定对象

例如

 <div rv-each-thing="data.things">
  <input type=button value="Click" rv-on-click="abc">
 </div>
function abc(event,rivetsBinding){
  rivetsBinding.thing //heres your thing :)
}

对不起,如果我迟到了,刚刚开始使用铆钉和遇到同样的问题。

解决方案:先绑定你的函数

例如你有一个函数:

function customOnClickCallback(event, item) {
    console.log(event);
    console.log(item);
    console.log(item.thing); // Instead of {{ thing }}
}

首先绑定要调用的函数(现在我将把它绑定到Body):

rivets.bind(document.getElementsByTagName("body")[0], {
    customOnClick: customOnClickCallback
});

则可以使用customOnClick作为rv-on-click

<input type=button value="Click" rv-on-click="customOnClick">

至于访问变量thing,它应该可以作为item.thing访问。

我是怎么做到的。只需复制并粘贴

下面的工作示例

解决方案1

<body>
    <div rv-each-book="model.books">
        <button rv-on-click="model.selectedBook | args book">
            Read the book {book}
        </button>
    </div>
</body>
<script type="text/javascript">
    rivets.formatters["args"] = function (fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function () {
            return fn.apply(null, args);
        };
    };
    rvBinder = rivets.bind(document.body, {
        model: {
            selectedBook: function (book) {
                alert("Selected book is " + book);
            },
            books: ["Asp.Net", "Javascript"]
        }
    });
</script>

或者另一种方法是binding event

解决方案2

<body>
    <div rv-each-book="books">
        <a rv-cust-href="book">
            Read the book {book}
        </a>
    </div>
</body>
<script type="text/javascript">
    rivets.binders['cust-href'] = function (el, value) {
        //el.href = '/Books/Find/' + value;
        //OR
        el.onclick = function () { alert(value); };
    }
    rvBinder = rivets.bind(document.body, {
        books: ["Asp.Net", "Javascript"]
    });
</script>
相关文章: