1

I have created a jQueryUI widget called "Picklist" using the widget factory. It works great. However, because it is a widget, it doesn't respond to the val() method.

I have a function that is looping through an array to assign data to web controls. For the most part, I can just use the jQuery method val() to assign the value. But that doesn't work for my widget.

I instead have to manually check if the widget exists on the control, and then call the widget version of val() to do the assignment. This seems terribly inefficient and the antithesis of good object oriented design.

    for (var i = 0; i < ControlData.length; i++)
    {
        var mapping = ControlData[i];
        $('#' + mapping.controlName).val(mapping.value);
        if ($('#' + mapping.controlName).data('Erik-Picklist'))
        {
            $('#' + mapping.controlName).Picklist("option", { val: mapping.value });
        }
    }

Is there a way to have val() map to a widget method on a certain element? I was thinking there might be a method I could call on the element that would map the val() method to the Picklist's val() method, but I haven't seen any example of that sort of thing.

4

1 回答 1

1

由于没有人回应,(这将教会我在星期五晚上发布一个问题)我花了很多时间试图找出一种方法来做到这一点。我能想出的最佳解决方案是受到https://stackoverflow.com/a/5760684/594602的启发

基本上,覆盖现有的 val() 函数,以便它检查当前元素的覆盖。

$.fn.old_val = $.fn.val;
$.fn.val = function ()
{
    var ErikVal = this.data('ErikVal');
    if (ErikVal)
    {
        return ErikVal.apply(this, arguments);
    }
    else
    {
        return this.old_val.apply(this, arguments);
    }
};

在 jQueryUI 小部件的 _create() 中,我添加了以下内容:

_create: function ()
{
    ...
    this.element.data('ErikVal', function ()
    {
        this.Picklist("option", { val: arguments[0] });
    });
},

我对此并不特别自豪,但它正在发挥作用。

于 2013-06-12T23:33:41.893 回答