简体   繁体   English

在对象类上实现jQuery作用域的最佳方法?

[英]Best way to implement jquery scoping on object classes?

In jQuery, I would like to define objects which act as classes (having private and public methods/properties). 在jQuery中,我想定义充当类的对象(具有私有和公共方法/属性)。 But also having a way to define a scope to that object. 但是也可以定义该对象的作用域。 To illustrate, consider this pseudocode: 为了说明,请考虑以下伪代码:

var myclass = function(context) {
    $.setscope(context);  // <-- this is not real, but I want something like this

    this.getItems = function() {
        return $('.grid');  // after calling `setscope` above, this will look in the scope of #page1
    };
}
var myclass_instance = new myclass("#page1");

Basically what this does, it forces jQuery to automatically use the scope of #page1 when ever I 'select' something from within myclass_instance. 基本上是这样做的,当我从myclass_instance中“选择”某项内容时,它将强制jQuery自动使用#page1的范围。 All code in it (public or private) should automatically use that scope. 其中的所有代码(公共或私有)都应自动使用该范围。 In other words, I shouldn't have to do return $('#page1').find('.grid'); 换句话说,我不必return $('#page1').find('.grid'); .

What I have now is a var context = '#page'; 我现在拥有的是var context = '#page'; defined on top, and then $(context).find(... everywhere in the class. This seems kinda redundant. 定义在顶部,然后$(context).find(...在类中的任何地方。这似乎有点多余。

Does anyone know if this is possible, and if not, the best way to implement this? 有谁知道这是否可能,如果没有,最好的方法是实现这一点?

Maybe something like this? 也许是这样的吗?

function myClass(context) {
  var _$ = $,
      $ = function() {
        return _$.find(context).apply(this, Array.prototype.slice.call(arguments));
      };

  this.getItems = function() { return $('.grid'); }
}

It's sounds like it's pretty simple abstraction you're looking for. 听起来您正在寻找的是非常简单的抽象。 Just define a method on MyClass that always queries the dom in the scope that you set on instantiation: 只需在MyClass上定义一个始终在实例化设置的范围内查询dom的方法即可:

var MyClass = function(scope) {
   this.scope = scope;
};

MyClass.prototype.get = function(selector) {
  return $(selector,this.scope);
}

MyClass.doStuff = function() {
   var $el = this.get('#someid');
   //do some stuff with $el;
}

var o = new MyClass('#scope');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM