以面向对象的方式使用 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1201286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using jQuery in object-oriented way
提问by JohnnyYen
Is it possible to achieve the following, using jQuery: I'd like to create two different objects that have different functions with the same name.
是否可以使用 jQuery 实现以下目标:我想创建两个具有相同名称的不同功能的不同对象。
var item = new foo();
item.doSomething();
var item2 = new bar();
item2.doSomething();
Furthermore, I'd like to be able to use the created items as "regular" jQuery objects - for example, to drag&drop the items and execute the correct doSomething() function when dragging has stopped.
此外,我希望能够将创建的项目用作“常规”jQuery 对象 - 例如,拖放项目并在拖动停止时执行正确的 doSomething() 函数。
回答by JohnnyYen
We've come up with a solution to the problem. It consists of 3 separate steps: first, the initial jQuery item must be created:
我们已经想出了解决问题的办法。它由 3 个独立的步骤组成:首先,必须创建初始 jQuery 项:
var item = $.create("div");
then create an instance of the javascript object you want to create and copy all of it's functions and properties to the jQuery item:
然后创建一个你想要创建的 javascript 对象的实例,并将它的所有函数和属性复制到 jQuery 项中:
$.extend( item, new foo.bar() );
Finally, initialize the object. Note that the constructor in previous step cannot be used for this since the "this" object is different.
最后,初始化对象。请注意,上一步中的构造函数不能用于此,因为“this”对象不同。
item.initialize();
After this, the object $(item) can be used like a regular jQuery object, plus it has functions and local variables like a regular javascript object.
在此之后,对象 $(item) 可以像常规 jQuery 对象一样使用,而且它具有像常规 javascript 对象一样的函数和局部变量。
item.doSomething(); var offset = $(item).offset();
So you can make DOM objects that have a "class" that can be used by jQuery. BTW, we used DUI to create namespaces.
因此,您可以创建具有可由 jQuery 使用的“类”的 DOM 对象。顺便说一句,我们使用 DUI 来创建命名空间。
Hopefully someone will find the solution helpful. It made our code much nicer.
希望有人会发现解决方案有帮助。它使我们的代码更好。
回答by ericsoco
i'm still pretty new to JS and jQuery, so feel free to shoot me down (aka 'provide constructive criticism'), but i've found that this works well for building JS objects meant to have an on-screen representation:
我对 JS 和 jQuery 还是很陌生,所以请随意批评我(也就是“提供建设性批评”),但我发现这对于构建具有屏幕表示的 JS 对象非常有效:
function SomeClass (params) {
// other properties and functions...
this.view = function () {
var e = $('<div />', {
'class': 'someClass'
});
return e;
}();
}
var someClassInstance = new SomeClass(params);
$('#someClassContainer').append(someClassInstance.view);
coming from a more traditional OOP background, and being used to using the MVC pattern, this is friendly for me. any suggestions welcome...
来自更传统的 OOP 背景,并且习惯使用 MVC 模式,这对我来说很友好。欢迎任何建议...
回答by PHearst
This is from Building Object-Oriented jQuery Plugins
(function($){
var MyPlugin = function(element, options){
var elem = $(element);
var obj = this;
var settings = $.extend({
param: 'defaultValue'
}, options || {});
// Public method - can be called from client code
this.publicMethod = function(){
console.log('public method called!');
};
// Private method - can only be called from within this object
var privateMethod = function(){
console.log('private method called!');
};
};
$.fn.myplugin = function(options){
return this.each(function(){
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('myplugin')) return;
// pass options to plugin constructor
var myplugin = new MyPlugin(this, options);
// Store plugin object in this element's data
element.data('myplugin', myplugin);
});
};
})(jQuery);
Test usage
测试使用
$('#test').myplugin();
var myplugin = $('#test').data('myplugin');
myplugin.publicMethod(); // prints "publicMethod() called!" to console
There's also a plugin based on this pattern, Taggerbased on this pattern.
还有一个基于这种模式的插件,基于这种模式的Tagger。
回答by Dima
<script type="text/javascript">// <![CDATA[
//Lets consider it as our class wrapper
(function( $ ) {
$.fn.testClass = function( initvar ) {
this.testMethod = function(status) {
this.test = status;
//lets call a method of a class
this.anotherMethod();
};
this.anotherMethod = function() {
alert("anotherMethod is called by object " + this.test);
};
this.getVars = function() {
alert("Class var set in testMethod: I am object " + this.test + "\nClass var set in constractor: " + this.class_var);
};
//lets init some variables here, consider it as a class constractor
this.class_var = initvar;
//THIS IS VERY IMPORTANT TO KEEP AT THE END
return this;
};
})( jQuery );
$(function() {
//Now lets create objects
var object1 = $(document.body).testClass("1");
var object2 = $(document.body).testClass("2");
//lets call method testMethod
object1.testMethod("1");
object2.testMethod("2");
//lets lets see what we have at the end
object1.getVars();
object2.getVars();
});
// ]]></script>
Reference: http://ajax911.com/jquery-object-oriented-plugins/
回答by AVProgrammer
I prefer a simpler method than posited by JohnnyYen et al.
我更喜欢一种比 JohnnyYen 等人提出的更简单的方法。
Basically, I create a class and assign the DOM element to a property.
基本上,我创建一个类并将 DOM 元素分配给一个属性。
eg.
例如。
/* CONSTRUCTOR: Tile */
function Tile(type, id){
this.type = type;
this.id = id;
this.DOM = $('#' + id);
}
/* METHOD: nudge */
Tile.prototype.nudge = function(direction){
var pos = this.DOM.offset();
var css_top = this.DOM.css("top");
var top = css_top.substring(0 , css_top.indexOf('px'));
var css_left = this.DOM.css("left");
var left = css_left.substring(0 , css_left.indexOf('px'));
var width = this.DOM.width();
var height = this.DOM.height();
switch(direction){
case 'up':
this.DOM.css({ "top": (+top - 75) + "px" });
break;
case 'left':
this.DOM.css({ "left": (+left - 75) + "px" });
break;
case 'right':
this.DOM.css({ "left": (+left + 75) + "px" });
break;
case 'down':
this.DOM.css({ "top": (+top + 75) + "px" });
break;
}
}
Note: this is untested code, but it illustrates my point.
注意:这是未经测试的代码,但它说明了我的观点。
回答by Robert Harvey
Not sure about the Object Orientation part, but jQuery has baked-in support for the kind of drag-and-drop capability you are describing.
不确定面向对象部分,但 jQuery 已经对您所描述的那种拖放功能提供了内置支持。
Using JQuery to Add Drag and Drop Supporthttp://geekswithblogs.net/AzamSharp/archive/2008/02/21/119882.aspx
使用 JQuery 添加拖放支持http://geekswithblogs.net/AzamSharp/archive/2008/02/21/119882.aspx
回答by Koding Sykosis
I know this question is old, but this is how I build my client side code.
我知道这个问题很老,但这就是我构建客户端代码的方式。
I use my own oop framework to build out my controllers/apps. If I set a class as a singleton, it's executed on doc ready and serves as my entry point for the client app.
我使用我自己的 oop 框架来构建我的控制器/应用程序。如果我将一个类设置为单例,它会在文档就绪时执行,并作为客户端应用程序的入口点。
https://github.com/KodingSykosis/jOOP
https://github.com/KodingSykosis/jOOP
Any code that needs to be globally accessible, I extend jQuery using the $.extend or $.fn.extend.
任何需要全局访问的代码,我都使用 $.extend 或 $.fn.extend 扩展 jQuery。
api.jquery.com/jQuery.extend
api.jquery.com/jQuery.extend
View or presentation style code, I use the jQueryUI widget factory. My controller classes are tasked with creating any elements required for a widget to instantiate. Any communication is facilitated through the use of events or callbacks.
视图或演示样式代码,我使用 jQueryUI 小部件工厂。我的控制器类的任务是创建小部件实例化所需的任何元素。通过使用事件或回调来促进任何通信。