Метод делегирования в Javascript / jQuery? - PullRequest
2 голосов
/ 05 августа 2009

У меня есть этот код:

var myWidget = $('#myWidget');

и другие подобные звонки:

myWidget.hide();
myWidget.slideToggle();

Это работает, конечно, потому что jQuery добавляет эти методы.

Теперь, допустим, я делаю некоторый рефакторинг, чтобы сделать myWidget правильным объектом со своими собственными пользовательскими методами и состоянием:

var myWidget = (function() {
    // private stuff
    var actualJQueryObject = $('#myWidget');
    return {
        publicMethod: function() {...},
        // MAGIC!
    }
})()

но я хочу, чтобы все вызовы, ожидающие, что объект jQuery, который находится вокруг моего кода, все еще работают, даже если myWidget больше не является объектом jQuery , потому что myWidget знает, как делегировать вызовы actualJQueryObject.

Возможно ли это?

Ответы [ 3 ]

3 голосов
/ 05 августа 2009

Вы также можете расширить свой объект jQuery с помощью другого объекта, который имеет ваши пользовательские методы:

var myWidget = function() {
    // private stuff
    var actualJQueryObject = $('#myWidget');

    var extensionMethods = {
        publicMethod: function() { alert('public method!'); }  
    }
    return $.extend(actualJQueryObject, extensionMethods);
}();

Просто будьте осторожны с именем вашего метода расширения , чтобы не конфликтовать с любой другой определенной jQuery-функцией.

Вы можете попробовать приведенный выше фрагмент здесь .

1 голос
/ 05 августа 2009

Один из вариантов - использование исходного объекта jquery в качестве прототипа.

function wrap(jqObject) {
    function MyNewType() {
        this.changeFontSize = function(a) { 
            this.css({fontSize : this.size});
        };
    }
    MyNewType.prototype = jqObject;
    return new MyNewType;
}
var obj = wrap($('#someitem'));
obj.size = 50;        // obj.size
obj.changeFontSize(); // obj.changeFontSize
obj.hide();           // $.hide
obj.fadeIn("slow");   // $.fadeIn
0 голосов
/ 05 августа 2009

Я написал плагин, который может вам помочь. Это в основном плагин для написания плагинов. Этот пост группы разработчиков объясняет это и имеет несколько примеров кода:

http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/72cf730045d4333a?hl=en&q=structure+plugin+authoring#72cf730045d4333a

И источник здесь:

http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js

EDIT:

Я создал функцию, аналогичную функциональности этого плагина:

jQuerify = function(fn) {
    function plugin() {
        var instantiate = false;

        // check to see if it has any prototyped methods (we only need one iteration to do this)
        for (var i in construct.prototype) {
            instantiate = true;

            break;
        }

        // if there are prototyped methods, return an instance (since an instance's return value won't vary)
        // otherwise just call it using apply so the return value can vary
        return instantiate
            ? new construct(this, arguments)
            : construct(this, arguments);
    }

    function construct(parent, args) {
        // 'this' will not mimic jQuery unless given the length property
        this.length   = 0;
        this.selector = parent.selector;
        this.context  = parent.context;

        // mimic 'this' in jQuery, but for the plugin namespace
        Array.prototype.push.apply(this, $.makeArray(parent));

        // return the constructors return value
        // should be 'this' if you want to chain the new namespace
        return fn.apply(this, arguments);
    }

    // copy all static properties and methods
    for (var i in fn) {
        plugin[i] = fn[i];
    }

    // allow .fn and copy all instance properties and methods; the last part is for IE
    plugin.fn = construct.prototype = plugin.prototype = fn.prototype;

    return plugin;
}

Это позволяет вам добавлять пользовательские объекты в jQuery как плагин, используя «this» для ссылки на выбранные объекты, а также позволяет вам иметь неограниченную глубину для вашего пространства имен:

function test1() {
    return this;
}
test1.prototype.getHtml1 = function() {
    return $(this).html();
}

function test2() {
    return this;
}
test2.prototype.getHtml2 = function() {
    return $(this).html();
}

function test3() {
    return this;
}
test3.prototype.getHtml3 = function() {
    return $(this).html();
}

jQuery.fn.test1                   = jQuerify(test1);
jQuery.fn.test1.fn.test2          = jQuerify(test2);
jQuery.fn.test1.fn.test2.fn.test3 = jQuerify(test3);

jQuery(function($) {

    alert($('body').test1().getHtml1());
    alert($('body').test1().test2().getHtml2());
    alert($('body').test1().test2().test3().getHtml3());

});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...