Jquery绑定困境

时间:2011-01-25 16:04:59

标签: jquery binding

我已经阅读了许多解释,但似乎我无法理解绑定的概念。在下面的代码中,我将如何制作这个'引用对象而不是调用'搜索'功能

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 >
<title></title>
</head>
<body>
<input id="inpt">
<script>
obj = {
  theElement: null,
  func1: function(inpt) {
    this.theElement = $(inpt);
    this.theElement.keyup(this.search);
  },
  search: function(e) {
    alert(this);  //'this' refers to the input element (#inpt) but I want it to refer to 'obj'
  }
};
obj.func1('#inpt');
</script>
</body>
</html>

希望有道理......

2 个答案:

答案 0 :(得分:2)

更改此行:

    this.theElement.keyup(this.search);

到此:

    this.theElement.keyup(function() {
        obj.search();
    }

或者这个:

    this.theElement.keyup($.proxy(this.search,this))

...使用jQuery.proxy()(docs)返回一个函数,该函数将使用正确的search()值调用this

还有the .bind() method可用于将上下文和参数绑定到函数,但它尚未得到广泛支持。

答案 1 :(得分:2)

两种方式:

1。使用你自己的闭包:

obj = {
  theElement: null,
  func1: function(inpt) {
    var self = this;
    this.theElement = $(inpt);
    this.theElement.keyup(function() {
        self.search();
    });
  },
  search: function(e) {
    alert(this);  //'this' refers to the input element (#inpt) but I want it to refer to 'obj'
  }
};

更多阅读:Closures are not complicated

修改:虽然patrick points outobj,但您已在self中对其进行了引用,因此技术上不需要obj = { theElement: null, func1: function(inpt) { this.theElement = $(inpt); this.theElement.keyup(jQuery.proxy(this.search, this)); }, search: function(e) { alert(this); //'this' refers to the input element (#inpt) but I want it to refer to 'obj' } }; 。以上是更通用的解决方案(特别是当您使用工厂函数而不是单例对象时)。

2。使用一个jQuery为您创建:

...通过jQuery.proxy

{{1}}

更多阅读:You must remember this