如何在javascript中引用另一个函数的fancytree变量

时间:2014-10-23 06:20:33

标签: javascript jquery

我正在尝试模块化我的javascript。我不是JS的新手,但我的知识并不像某些人那么先进。对于擅长JS的人来说,这可能是一个简单的问题。

在下面的代码中 - 如何获得在'handleTreeBrowser'函数中创建的fancytree的句柄,我需要'newTopCategoryForm'的成功函数中的引用?有没有比在更高范围内创建变量更好的选择?

我尝试通过JQuery搜索元素,认为它已经被fancytree属性和amp;方法等...但重新加载功能未定义。

/**
 The edit related products page controls
 **/
var ManageCategories = function () {

    var handleFormButtons = function () {

        console.debug('initialising buttons...');
        $(document).on('click','.new-topcategory-button', function(event)
        {
            event.preventDefault ? event.preventDefault() : event.returnValue = false;
            console.debug('clicked...');
            console.debug($(this).attr('href'));

            var refreshURI = $(this).attr('href');
            $.get(refreshURI)
                .success(function(data,status,xhr){
                    // need to do something with the data here.
                    $('#categoryFormContainer').html(data);
                    RichText.init();
                });

        })
    };

    var handleNewTopCategoryForm = function () {
        console.debug('initialising top category form');
        $(document).on('submit', '#topCategoryForm', function(event)
            {
                console.debug("submitting the new top category form");
                var form = $(this);
                var token = $("meta[name='_csrf']").attr("content");
                var header = $("meta[name='_csrf_header']").attr("content");
                var formData = form.serializeArray();

                $(this).find('button').attr('disabled');


                event.preventDefault ? event.preventDefault() : event.returnValue = false;

                var jqxhr = $.ajax(
                    {
                        url: form.attr('action'),
                        type: 'POST',
                        data: formData,
                        headers: {'X-CSRF-TOKEN': token}
                    }
                )
                    .success(function (data, status, xhr) {
                        var messageContainer = $('#messageContainer');
                        var source = $('#ui_message_template').html();
                        var template = Handlebars.compile(source);
                        var html = template(data);
                        messageContainer.html(html);
                        data.form = form;

                        // Reload the tree from previous `source` option
                        $('#tree').reload().done(function(){
                            alert("reloaded");
                        });

                        // we trigger this publish method so the browser can update itself
                        $.Topic( 'topCategoryAdded' ).publish( data );


                    })
                    .fail(function (data, status, xhr) {
                        var messageContainer = $('#messageContainer');
                        var source = $('#ui_message_template').html();
                        var template = Handlebars.compile(source);
                        var html = template(data);
                        messageContainer.html(html);

                        // we have to process the form validation failures here.

                    });
            }

        );


    }

    var handleTreeBrowser = function () {
        console.debug('initialising trees.');
        $('#tree').fancytree({
            source: {
            url: '/admin/categories/json/full_category_tree',
            cache: false
            },
            extensions: ["dnd"],
            checkbox: false,
            selectMode: 2,
            activate: function(event, data) {
                console.debug(event);
                console.debug(data);
                console.debug(data.node.key())
            },
            dnd: {
                autoExpandMS: 400,
                focusOnClick: true,
                preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
                preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
                dragStart: function(node, data) {
                    /** This function MUST be defined to enable dragging for the tree.
                     *  Return false to cancel dragging of node.
                     */
                    return true;
                },
                dragEnter: function(node, data) {
                    /** data.otherNode may be null for non-fancytree droppables.
                     *  Return false to disallow dropping on node. In this case
                     *  dragOver and dragLeave are not called.
                     *  Return 'over', 'before, or 'after' to force a hitMode.
                     *  Return ['before', 'after'] to restrict available hitModes.
                     *  Any other return value will calc the hitMode from the cursor position.
                     */
                    // Prevent dropping a parent below another parent (only sort
                    // nodes under the same parent)
                    /*           if(node.parent !== data.otherNode.parent){
                     return false;
                     }
                     // Don't allow dropping *over* a node (would create a child)
                     return ["before", "after"];
                     */
                    return true;
                },
                dragDrop: function(node, data) {
                    /** This function MUST be defined to enable dropping of items on
                     *  the tree.
                     */
                    data.otherNode.moveTo(node, data.hitMode);
                }

            }

        });

    }




    return {
        //main function to initiate the module
        init: function () {

            handleTreeBrowser();
            handleFormButtons();
            handleNewTopCategoryForm();


        }
    };
}();

2 个答案:

答案 0 :(得分:2)

实际上,以前的答案通常对于javascript通常都没问题,所以我将其保留为好。但无论出于何种原因,fancytree树插件在初始化时都不会返回自身的实例。有点奇怪。

因此,针对此特定问题的实际修复是使用fancytree api中的此函数。

// from handleform.success
// Reload the tree from previous `source` option
var tree = $("#tree").fancytree('getTree');
tree.reload().done(function(){
    alert("reloaded");
});

答案 1 :(得分:0)

你可以在函数中声明fancytree变量,js闭包允许你从其他函数中访问它:

var ManageCategories = function () {
    var fancytree = null;
    // in handleform.success:
        if (fancytree !== null)
            fancytree....
    // in handleTreeBrowser:
        fancytree = $("#tree').fancytree(....

这个fancytree只能通过这两个功能访问。