开发者

jQuery widgets, not how I thought they were?

开发者 https://www.devze.com 2023-03-21 06:36 出处:网络
I thought jQuery widgets were jQuery objects that were handily linked to DOM objects (so you could store state, for example, or handle events), but I\'m having some problem with understanding the inst

I thought jQuery widgets were jQuery objects that were handily linked to DOM objects (so you could store state, for example, or handle events), but I'm having some problem with understanding the instance model here. I have an object as such ;

var xs_widgets = {

    jQuery : $,

    options: { },

    _create: function () {
        this.make_sortable() ;
    },

    _init: function () { alert ( 'init' ) ; }

    make_sortable: function () { alert ( 'make-sortable' ) ; }
}

I bind it to jQuery with ;

jQuery.widget( "ui.xs_widgets", xs_widgets );

And then, I try to bind some DOM elements to the widget ;

$('li.widget').xs_widgets();

Now here's the thing. I thought that each <li class="widget"> got a jQuery object attached, but from what I can gather there's a global xs_widget object regardless, and it gets fed the jQuery objects from the query above, and you yourself have to deal with instance data? I thought the whole point of the widgets was to avoid the overhead of dealing with instanc开发者_运维知识库es? The above code run against HTML that contains, say, two <li> elements yields ;

make-sortable
init
make-sortable
init

I was expecting ;

make-sortable
init
init

Oh, please help! I'm reading tutorials and articles, but I seem to be missing something vital somewhere.


Your xs_widgets function widget gets called once for each matching element in your selector (so, twice with two tags).

I thought that each got a jQuery object attached.

They do. Which is why _create and _init are both called twice. However, the create method will only be called once when adding the widget to the element. If you call $('li.widget').xs_widgets(); again right after your first call, you'll only get:

init
init

Here's an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号