代码之家  ›  专栏  ›  技术社区  ›  sairfan

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

  •  -2
  • sairfan  · 技术社区  · 7 年前

    <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

    1 回复  |  直到 7 年前
        1
  •  2
  •   sairfan    7 年前

    在工作中,我发现了不同的方法可以提供帮助,如果有人可以得到帮助,或者需要改进,请在这里发布。

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

    创建自定义活页夹

    <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 当我在主干上使用铆钉时,我还可以利用主干视图上的事件

    // backbone view
    events: {
        'click #linkid': 'linkclicked'
    },
    linkclicked: function (e){
        console.log(this.model.get("Name"));
    },
    
    <td><a id="linkid" href="#">{ item:Name }</a></td>