简体   繁体   English

带骨干的铆钉:href/onclick 属性上的调用方法(函数)

[英]rivets with backbone: calling method (function) on href/onclick attribute

what i'm trying to do is call a funcation like below, further i want to pass current element (item) to function as parameter.我想要做的是调用如下所示的函数,此外我想将当前元素(项目)作为参数传递。

<tr rv-each-item="items:models">
    <td><a href="javascript:selectedItem(item);">{ item:Name }</a></td>
</tr>

var selectedItem = function (item)
{
    console.log(item);
}

while searching around i found below discussion helpful but could not solve my problem as it does not implement backbone在四处搜索时,我发现下面的讨论很有帮助,但无法解决我的问题,因为它没有实现主干

https://github.com/mikeric/rivets/issues/554 https://github.com/mikeric/rivets/issues/554

Rivets.js: When button is clicked, call a function with an argument from a data binding Rivets.js:单击按钮时,使用数据绑定中的参数调用函数

While working around i found different approaches that can help, posting here if someone can get help or improve if there is any thing needs to.在解决问题的过程中,我发现了可以提供帮助的不同方法,如果有人需要帮助或改进,请在此处发布。

Option 1选项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>

Option 2 Create a custom binder选项 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>

Option 3 As I was using rivetsjs with backbone, i can also get advantage of events on backbone view选项 3当我使用带有主干的 rivetsjs 时,我还可以利用主干视图上的事件

// backbone view
events: {
    'click #linkid': 'linkclicked'
},
linkclicked: function (e){
    console.log(this.model.get("Name"));
},

<td><a id="linkid" href="#">{ item:Name }</a></td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM