Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jQuery in object-oriented way

Tags:

jquery

oop

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.

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.

like image 732
JohnnyYen Avatar asked Jul 29 '09 15:07

JohnnyYen


People also ask

Is jQuery object oriented?

Class-based OOP languages are a subset of the larger family of OOP languages which also include prototype-based languages like JavaScript and Self. jQuery is a library for JavaScript that makes certain things easier to accomplish.

Can JavaScript be used for OOP?

JavaScript is a very good language to write object oriented web apps. It can support OOP because supports inheritance through prototyping also properties and methods. You can have polymorphism, encapsulation and many sub-classing paradigms.

Can we create class in jQuery?

jQuery – create object oriented classes in jQueryCreate an object oriented style with jQuery. Make use of the constructor() method and access public and private methods from within the class scope.

What does $() do in jQuery?

$(document) wraps a jQuery instance around the document object. ( $ is just an alias for jQuery .)


1 Answers

We've come up with a solution to the problem. It consists of 3 separate steps: first, the initial jQuery item must be created:

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:

$.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.

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.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.

Hopefully someone will find the solution helpful. It made our code much nicer.

like image 190
JohnnyYen Avatar answered Oct 24 '22 14:10

JohnnyYen