使用jQuery将构造函数方法作为处理程序附加

时间:2017-03-11 02:38:26

标签: javascript

所以,我有这个:

    def create(self, validated_data):
        # for create - there is always name; we have already checked that in validation
        # TODO Further check for group-name clash - if yes, update the same group
        owner = validated_data['owner']
        name = validated_data['name']

        # created is a boolean telling us if a new DeviceGroup was created
        group, created = DeviceGroup.objects.update_or_create(name=name, defaults={'owner': owner})

        tokens = [d['token'] for d in validated_data['devices'] ]
        BaseDevice.objects.filter(token__in=tokens, owner=owner).update(group=group)
        return group

并且它不起作用,但是如果我改变这一行:

function foo(){

  var that = this;

  this.elements = [
    $bar = $('.bar'),
    $foo = $('.foo')
  ];

  this.example = function(){
    alert("a");
  }

  this.elements.$bar.on('click', that.example);
}

这个:

  this.elements.$bar.on('click', that.example);

也就是说,将方法包装到匿名函数中,它确实有用......

编辑:如果方法不在构造函数中,它也有效。

1 个答案:

答案 0 :(得分:1)

我认为您在当前代码中附加方法的方式没有任何问题。虽然我注意到你已经将你的DOM元素称为:

this.elements = [
    $bar = $('.bar'),
    $foo = $('.foo')
];

this.elements.$bar

相反,尝试将它们指定为对象:

this.elements = {
    $bar : $('.bar'),
    $foo : $('.foo')
 };

然后在你的代码中:

this.elements.$bar.on('click', that.example);

以下是一个示例jsfiddle以获取更多详细信息: http://jsfiddle.net/b1bsc1rd/

希望这会对你有所帮助