OO JQuery and classes

2019-02-01 11:31发布

I'm working on a site and using JQuery for essentially the first time. I've mostly used MooTools for previous projects, and I have a few widget classes I've written using the MooTools Class structure. I'd like to port them over to JQuery, but it looks to me like there is nothing similar to the MooTools functionality when it comes to object classes.

I've searched around a bit, and haven't found much on it. Digg appears to have rolled their own, but I'm not sure if this is something I should be using. Is there a better way? How object-oriented do people normally get with JQuery? What's the usual method of encapsulating a UI widget (or any functional class structure)?

I'll post a fake example of a possible MooTools widget class:

var ZombatWidget = new Class({
    Extends: BaseWidget,
    widgetPropertyX = 'prop1',
    widgetPropertyY = 'prop2',
    attach = function(el) {
        var f = function() { 
            //do something widgety
        };
        el.addEvent('dblclick',f);
        el.addClass('widgetized');
    }
});

var z = new ZombatWidget();
z.attach($('widgetDiv'));

What I've got is a lot bigger than that, but you get the idea. Do I need to convert this to the prototype method of class/inheritance structuring? How would you write this kind of object class using JQuery?

8条回答
Rolldiameter
2楼-- · 2019-02-01 12:13

You might find this approach useful to the task at stake: building an object-oriented jquery plugin.

And this article on Ajaxian "a real OO class system with jquery".

查看更多
放荡不羁爱自由
3楼-- · 2019-02-01 12:21

There are third party javascript class implementations that provide very powerful introspection capabilites. I would like to particularly highlight JS.Class and Joose. While JS.Class is modeled after Ruby, Joose is modeled after Moose. I am not a mootools user so I can not comment on their advantages/disadvantages with respect to mootools. But I would summarize their key features.

JS.Class has a strong focus on simulating the Object oriented features of Ruby and does a pretty good job at that. It provides a powerful library modeled after the standard library of Ruby and also comes with a well integrated package management and testing framework.

Joose, while provides no testing framework/package management facilites, excels in terms of advanced attribute management facilities, filters and better introspection facilities.

Both of them have really good documentation and can be used in browser as well as server.

查看更多
登录 后发表回答