Rivets.js:单击按钮时,使用数据绑定中的参数调用函数

时间:2015-09-21 10:56:04

标签: javascript rivets.js

这太令人生气了。它似乎应该如此简单,但我找不到神奇的咒语。

以下是我需要做的要点:

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

这应该说明我需要做什么。我尝试过很多不同的东西,但似乎没什么用。

3 个答案:

答案 0 :(得分:5)

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

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

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

使用它可以访问特定对象

例如

 <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 :)
}

答案 1 :(得分:0)

以下是我如何度过这一点。只需复制并粘贴下面的工作示例

<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>

或另一种方法是绑定事件

<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>

答案 2 :(得分:0)

对不起,如果我迟到了,刚开始使用Rivets并遇到了相同的问题。

解决方案:首先绑定您的功能

例如,您有一个功能:

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的形式访问。

相关问题