2017-09-27 45 views
-2

我想要做的就是调用一个函数如下,进一步我想通过当前元素(项目)作为参数。与骨干铆钉:href/onclick属性调用方法(函数)

<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

+0

我写了一个你分享的问题的答案。过去我曾使用铆钉与骨干。请分享一个[mcve],说明为什么它不适用于主干。你可能做错了什么。 –

回答

0

工作时左右,我发现不同的方法可以解决不了我的问题帮助,张贴在这里如果有人可以得到帮助或改善,如果有任何事情需要。

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