jQuery自定义事件在第一次传递时没有触发,否则会起作用?

时间:2015-03-25 08:16:22

标签: jquery jquery-plugins jquery-events

我从我正在构建的插件中发出自定义事件,虽然它在正常调用时都能正常工作,但在我的插件初始化功能期间它不起作用,我不是确定为什么。我将我的插件附加到我的页面:

$(document).ready(function() {
    $('input.tagger').suggest();        
});

这是我的删节插件,其中包含相关内容:

(function($) {
    $.fn.suggest = function() {
        // Provide an accessor to the bound element
        var self = this;
        var containerElement, 
            wrapperElement,
            submissionElement, // this
            tagsElement, 
            inputElement, 
            suggestionElement;

        var currentTags = new Array();

        // Create a new tag when asked
        var createNewTag = function(tag) {
            // trim and convert the text to lowercase
            tagText = $.trim(tag.toLowerCase());

            tagsElement.append('<div class="'+ tagText +'">'+ tagText +'<span class="remove">X</span></div>');
            currentTags.push(tagText);
            inputElement.val("");
            containerElement.trigger('tag:added');
        }

        var actions = function() {

            containerElement.on('tag:added', function() {
                console.log(wrapperElement.width());
                console.log(tagsElement.outerWidth());
                var inputElementWidth = wrapperElement.width() - tagsElement.outerWidth() - 1; // Why minus one? Who knows.
                inputElement.css({'width': inputElementWidth});
            });
        }

        // init
        (function() { 

            // 'containerElement' and such like defined and added to the DOM here.

            // Define some variables that refer to elements that I have dynamically created above. Once all the elements are setup, check to see if there's any default values in the input that we need to include
            var defaultTags = self.val().split(" ");
            $.each(defaultTags, function(index, defaultTag) {
                createNewTag(defaultTag);
            });
        }());
        return this;
    }
}(jQuery));

正如您所看到的,我首先将init函数作为IIFE运行,并调用createNewTag函数,该函数应该发出tag:added事件。如果我在代码的其他部分createNewTag函数外部调用init,则tag:added事件发生,而如果从init内调用, createNewTag将运行,但不会触发任何事件。

为什么会这样?

0 个答案:

没有答案