【问题标题】:rivets with backbone: calling method (function) on href/onclick attribute带骨架的铆钉:在 href/onclick 属性上调用方法(函数)
【发布时间】:2018-03-09 03:53:29
【问题描述】:

我想要做的是调用如下所示的函数,进一步我想将当前元素(项目)作为参数传递给函数。

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

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

在四处搜索时,我发现下面的讨论很有帮助,但无法解决我的问题,因为它没有实现骨干

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

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

【问题讨论】:

  • 我为您分享的问题写了一个答案。而且我过去使用过带骨架的铆钉。请分享minimal reproducible example 来说明为什么它不适用于骨干网。你可能做错了什么。

标签: javascript function backbone.js href rivets.js


【解决方案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>

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2019-07-08
    相关资源
    最近更新 更多