简体   繁体   中英

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

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

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

<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

<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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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