使用rivets.js声明绑定的正确上下文

时间:2014-10-26 09:17:51

标签: backbone.js rivets.js

我正在使用: 1.Adapter:

rivets.adapters[':'] = {
      subscribe: function(obj, keypath, callback) {
        obj.on('change:' + keypath, callback)
      },
      unsubscribe: function(obj, keypath, callback) {
        obj.off('change:' + keypath, callback)
      },
      read: function(obj, keypath) {
        return obj.get(keypath)
      },
      publish: function(obj, keypath, value) {
        //console.log(obj);
        obj.set(keypath, value);

      }
    }

2.Collection:

var FriendsList = Backbone.Collection.extend({
    model: Friend,
    initialize : function (Friend,options) {

        this.addFriend();

    },
    addFriend : function () {
        this.add ( this.f = new this.model() );
    }
}); 
window.friends = new FriendsList();
rivets.bind($("#friendsTable tfoot"), {friends:window.friends})

3.声明

<tr class="totals">
        <td colspan="2">
        <a href='javascript:' class="btn btn-primary" rv-on-click="friends.addFriend">Add Friend</a></td>
        <td class="b r">Total</td>
        <td class="total r b"></td>
    </tr>

使用时。 addFriend的符号上下文设置为target元素 - 如何使用:notation强制“this”指向集合实例?

1 个答案:

答案 0 :(得分:0)

我不知道你为什么要这样做,或者为什么你的代码是这样的结构,

但是如果你真的想这样做,你可以用这种方式配置铆钉。

默认铆钉配置:

rivets.configure({
 // Attribute prefix in templates
 prefix: 'rv',

 // Preload templates with initial data on bind
 preloadData: true,

 // Root sightglass interface for keypaths
 rootInterface: '.',

 // Template delimiters for text bindings
 templateDelimiters: ['{', '}'],

 // Augment the event handler of the on-* binder
 handler: function(target, event, binding) {
   this.call(target, event, binding.view.models)
 }
})

将处理程序修改为

handler: function(target, event, binding) {
   this.call(binding.model, event, binding.view.models)
 }

这样用于绑定的模型将成为处理程序的上下文