In jQuery, I would like to define objects which act as classes (having private and public methods/properties). 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. 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');
.
What I have now is a var context = '#page';
defined on top, and then $(context).find(...
everywhere in the class. This seems kinda redundant.
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:
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.